ruby-on-rails - rails : checking modified fields

标签 ruby-on-rails

首先,我生成了名为“item”的脚手架

我想检查项目的哪些字段被修改。我已经尝试了两种可能的尝试,但都行不通。

第一次尝试!

def edit
  @item = Item.find(params[:id])
  @item_before_update = @item.dup
end

def update
  @item = Item.find(params[:id])
  # compare @item_before_update and @item here, but @item_before_update is NIL !!!
end

第二次尝试!
我寻找将数据从 View 传递到 Controller 的方式,但我不能。
编辑.html.erb
<% @item_before_update = @item.dup %> # I thought @item_before_update can be read in update method of item controller. But NO.
<% params[:item_before_update] = @item.dup %> # And I also thought params[:item_before_update] can be read in update mothod of item controller. But AGAIN NO

<% form_for(@item) do |f| %>
# omitted
<% end %>

请让我知道如何解决这个问题:(

最佳答案

具有未持久化更改的属性将对 changed? 响应 true

@item.title_changed? #=> true

您可以使用 changed 获取一组已更改的属性。
@item.changed #=> ['title'] 

为您 #update行动,你需要使用attributes=要更改对象,则可以使用 changedchanged?在坚持之前:
def update
  @item = Item.find(params[:id])
  @item.attributes = params[:item]
  @item.changed #=> ['title']
  ... do stuff
  @item.save
end

关于ruby-on-rails - rails : checking modified fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190471/

相关文章:

ruby-on-rails - Jquery 库在 Rails 4 中无法正常工作

ruby-on-rails - 如何设置设计邮件发件人名称?

ruby-on-rails - 将列表插入redis中的列表

ruby-on-rails - rails : How to choose which js file a controller action to render?

ruby-on-rails - 使用 Rails 将便士转换为货币

ruby-on-rails - nokogiri:生产环境中的重定位错误

ruby-on-rails - Ruby on Rails 继承语法

ruby-on-rails - `after_create` 和 `after_save` 有什么区别,什么时候使用哪个?

html - html.erb 文件中的类名分隔

mysql - ActiveRecord 数据库连接的回调?