开发者

Rails: checking modified fields

开发者 https://www.devze.com 2022-12-19 04:26 出处:网络
First, I\'ve generated scaffold called \'item\' I\'d like to check which fields of the item are modified. and I\'ve tried two possible attempts, those\'re not work tho.

First, I've generated scaffold called 'item'

I'd like to check which fields of the item are modified. and I've tried two possible attempts, those're not work tho.

First Attempt!

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

Second Attempt! I looked for the way passing data from view to controller and I couldn't. 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 m开发者_开发技巧othod of item controller. But AGAIN NO

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

Please let me know how to solve this problem :(


Attributes that have changes that have not been persisted will respond true to changed?

@item.title_changed? #=> true

You can get an array of changed attributes by using changed

@item.changed #=> ['title'] 

For your #update action, you need to use attributes= to change the object, then you can use changed and changed? before persisting:

def update
  @item = Item.find(params[:id])
  @item.attributes = params[:item]
  @item.changed #=> ['title']
  ... do stuff
  @item.save
end
0

精彩评论

暂无评论...
验证码 换一张
取 消