Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: checking modified fields

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 :(

like image 694
Hongseok Yoon Avatar asked Feb 03 '10 08:02

Hongseok Yoon


1 Answers

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
like image 145
Ben Avatar answered Oct 08 '22 21:10

Ben