[英]How do you write a Rails form that saves only changed items?
I've got a form on which the user can edit many objects simultaneously. 我有一个表格,用户可以在该表格上同时编辑许多对象。 The form uses form_tag
, and many instances (via iteration) of text_field_tag
, select_tag
, and check_box_tag
. 该表单使用form_tag
以及text_field_tag
, select_tag
和check_box_tag
许多实例(通过迭代)。
As currently constituted, submitting the form causes the controller action to call .save!
按照当前的构成,提交表单会使控制器操作调用.save!
on every single object that might have been updated, regardless of whether the user made any changes to it. 在每个可能已更新的对象上,无论用户是否对其进行了任何更改。 This is obviously not ideal. 这显然是不理想的。
How can I alter the form and controller action so that they only save the objects that need to be saved? 如何更改表单和控制器操作,使其仅保存需要保存的对象?
I would do this by setting up before_save filters on each of the corresponding models. 我可以通过在每个相应的模型上设置before_save过滤器来做到这一点。 Load the saved state of that current object, and compare the relative attributes. 加载该当前对象的保存状态,并比较相对属性。 If none of the attributes changed, return false: 如果所有属性均未更改,则返回false:
class Post < ActiveRecord::Base
before_save :check_for_changes
private
def check_for_changes
saved = Post.find(self.id)
should_save = false
if saved.body != self.body || saved.title != self.title
should_save = true
end
should_save
end
end
That said, i think the in place editing gem is a good idea. 也就是说,我认为就地编辑gem是个好主意。 There may be another gem out there that does this as well. 可能还有另一个宝石也可以做到这一点。 I'm just personally not aware of it. 我个人并不知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.