我有这个代码,你可以看到我有两个参数。我在一个表中创建了新字段,在另一个表中我更新了字段。
我需要将它们粘贴到MySQL中。一切都很酷,但我有一个问题:如何进行交易,因为我不想只在其中一个数据库中粘贴(更新或创建)。因为现在,如果我填充了一个参数,则表创建或更新,但我想将它们全部放在ONCE的数据库中。所以我的问题是......如何做交易以避免粘贴其中一个?
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
并且在日志中出现此错误:(如果我将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/ruby-1.9.3-p0@rails314/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
Rendered /home/parallels/.rvm/gems/ruby-1.9.3-p0@rails314/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /home/parallels/.rvm/gems/ruby-1.9.3-p0@rails314/gems/actionpack-3.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (2.8ms)
答案 0 :(得分:0)
ActiveRecord::Base.transaction do
...
end
将在事务中包装块。如果某些模型具有不同的数据库连接,则在该特定类上调用事务以使事务在正确的连接上发生。