首先,我已经生成了名为“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
第二次尝试!我在寻找从视图到控制器传递数据的方法,但是我找不到。
edit.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?
只为您的模型实例定义,而不是为您的属性(即整数、字符串等)定义。截至 Rails 3.2.3,您仍需要使用@object.attribute_changed?
来执行每个属性检查。http://api.rubyonrails.org/classes/ActiveModel/Dirty.html - jibiel