首先,我生成了名为“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=
要更改对象,则可以使用 changed
和 changed?
在坚持之前: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/