2012-03-24 3 views
0

두 개의 매개 변수가 있음을 알 수 있듯이이 코드가 있습니다. 그리고 나는 한 테이블에서 새로운 필드를 만들고, 다른 테이블에서는 필드를 업데이트했습니다.레일 3 + 트랜잭션 : 어떻게 작동합니까?

MySQL에 붙여 넣어야합니다. 모든 것이 멋지지만 질문이 있습니다. 데이터베이스에 붙여 넣기 (업데이트 또는 생성) 만하지 않기 때문에 트랜잭션을 수행하는 방법입니다. 왜냐하면 지금까지 하나의 params를 채우면 테이블이 업데이트되었지만 한 번에 모두 데이터베이스에 저장하려고합니다. 그래서 내 질문은 ... 어떻게 그들 중 하나를 붙여 피하기 위해 거래를 할 수 있습니까?

json_grid_params = ActiveSupport::JSON.decode(params[:grid_json]) 
json_form_params = ActiveSupport::JSON.decode(params[:form_json]) 

    json_grid_params.each do |json_grid_params| 
    report  = Report.find(:all, :conditions => ["wat_id in (?)", json_grid_params["wat_id"].to_i]) 

     report.each do |r| 
      rr = r.update_attributes(:percent_money => json_grid_params["percent_money"], 
            :percent_item => json_grid_params["percent_item"], 
            :trend   => json_grid_params["trend"]) 
     end 

     form = FormAnswer.create(json_form_params) 

업데이트 :
ActiveRecord::Base.transaction do 
    json_grid_params = ActiveSupport::JSON.decode(params[:grid_json]) 
    json_form_params = ActiveSupport::JSON.decode(params[:form_json]) 
      json_grid_params.each do |json_grid_params| 
     report = Report.find(:all, :conditions => ["wat_id in (?)", json_grid_params["wat_id"].to_i]) 
      report.each do |r| 
       rr = r.update_attributes(:percent_money => json_grid_params["percent_money"], 
          :percent_item => json_grid_params["percent_item"], 
          :trend   => json_grid_params["trend"]) 
      rr.save! 
      form = FormAnswer.create(json_form_params) 
      #form.save! 
      end 
     end 
end 

및 로그에

이 오류가있다 : (i가 빈 grid_params을 떠날 경우)

NoMethodError (undefined method `save!' for true:TrueClass): 
    app/components/report_grid.rb:122:in `block (4 levels) in <class:ReportGrid>' 
    app/components/report_grid.rb:118:in `each' 
    app/components/report_grid.rb:118:in `block (3 levels) in <class:ReportGrid>' 
    app/components/report_grid.rb:116:in `each' 
    app/components/report_grid.rb:116:in `block (2 levels) in <class:ReportGrid>' 
    app/components/report_grid.rb:113:in `block in <class:ReportGrid>' 

Rendered /home/parallels/.rvm/gems/[email protected]/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms) 
Rendered /home/parallels/.rvm/gems/[email protected]/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms) 
Rendered /home/parallels/.rvm/gems/[email protected]/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (2.8ms) 

답변

0
ActiveRecord::Base.transaction do 
    ... 
end 

는 트랜잭션에 블록을 포장합니다. 일부 모델에 다른 데이터베이스 연결이있는 경우 해당 특정 클래스에서 트랜잭션을 호출하여 올바른 연결에서 트랜잭션이 발생하도록하십시오.

+0

업데이트 : 내 코드를 확인하고 업데이트했습니다. –

+0

내 경우에는 작동하지 않습니다. (알지 못합니다. –

+0

rr.update_attributes가 즉시 저장하고 true를 반환합니다. 그러면 유효하지 않은 true로 저장하려고합니다. http://apidock.com/rails/ActiveRecord/를 참조하십시오. Base/update_attributes – DGM