如何在不实际保存更改的情况下完成update_attributes

Jac*_*R-G 3 activerecord ruby-on-rails associations update-attributes ruby-on-rails-3

可能重复:
Rails update_attributes没有保存?

从根本上说,我想做一个ActiveRecord"update_attributes",同时让ActiveRecord更改为待处理.有没有办法实现这个目标?如果你想知道为什么我会想要这个,请继续阅读.

我有一个由三部分组成的表单:静态部分(彼此独立的文本字段),一组选择(填充条目时增长),以及显示选择对一组依赖对象的影响的部分.更改选择需要往返服务器以确定效果,并且某些选择会影响将来选择的选择.选择被建模为基本模型的has_many关联.例如(注意[]条目指定HTML-SELECTs)

Include [section]
  Exclude [subsection]
  Exclude [subsection]
Include [section]
  Exclude [subsection]
...
Run Code Online (Sandbox Code Playgroud)

我已将表单设置为典型的嵌套属性表单.当选择被更改时,我使用AJAX回发字段,以便获得典型的params哈希值(例如params [:basemodel] [associated_models_attributes] [0] [:field_name]).我想把它变成一个未保存的ActiveRecord,这样我用来生成原始页面部分的部分就可以用来生成JS响应(我正在使用js.erb文件).使用Basemodel.new(params [:basemodel])给出错误

"ActiveRecord::RecordNotFound (Couldn't find AssociatedModel with ID=1 for Basemodel with ID=)
Run Code Online (Sandbox Code Playgroud)

这种情况正在发生(我认为),因为现有关联记录(当前记录中包含非空ID)的ID与从"新"调用生成的空白ID不匹配.

我可以做一些真正的kludgy并创建一些看起来像ActiveRecord的东西(至少足以满足我的偏见)但我必须认为这是一个很常见的问题,它有一个很好的解决方案.

Hck*_*Hck 7

取决于ActiveRecord :: Persistence#update_attributes的来源

# File activerecord/lib/active_record/persistence.rb, line 127
def update_attributes(attributes)
  # The following transaction covers any possible database side-effects of the
  # attributes assignment. For example, setting the IDs of a child collection.
  with_transaction_returning_status do
    self.attributes = attributes
    save
  end
end
Run Code Online (Sandbox Code Playgroud)

您可以使用分配属性到模型

model.attributes = attributes
Run Code Online (Sandbox Code Playgroud)

其中attributes是模型字段的哈希等.