views:

49

answers:

1

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 mothod of item controller. But AGAIN NO

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

Please let me know how to solve this problem :(

+3  A: 

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
Ben
This is cool, but not work in update action of the item controller. What's wrong?
Hongseok Yoon
I've added an example update method. The reason it wasn't working is that you retrieved @item from the database, so it was not changed. You then need to update it with your params from the submitted form, then you can get the `changed` status, and persist if you wish.
Ben