简体   繁体   English

您如何编写仅保存更改的项目的Rails表单?

[英]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_tagselect_tagcheck_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.

相关问题 你通常如何在 Rails 中对项目进行排序? - How do you normally sort items in Rails? 您如何编写Rails验证,该验证以是否在表单中填写其他字段为条件? - How do you write a rails validation that is conditional upon if other fields were filled out within a form? Ruby on Rails路由,如何强制更改子域/域 - Ruby on Rails routing, how do you force a subdomain / domain changed Rails多记录表单仅保存最后一条记录的参数 - Rails multi-record form only saves parameters for last record 如何在rails中验证表单中的照片 - How do you validate photos in a form in rails 你如何在 Rails 中上传 model 中的所有项目 - How Do you upload all items in a model in rails 你如何在Rails 3.1中用Sprockets编写DRY,模块化coffeescript? - How do you write DRY, modular coffeescript with Sprockets in Rails 3.1? 您如何在Rails中正确编写json响应destroy方法? - how do you write json response destroy methods correctly in rails? 你如何在Ruby on Rails中编写一个内联的条件三元运算符? - How do you write a conditional ternary operator inline in Ruby on Rails? 你怎么写Rails cron作业什么时候宝石? - How do you write a Rails cron job Whenever gem?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM