views:

24

answers:

1

I have a model Article, that has_many Revisions. Revisions have a variety of columns storing all the information about the Article. The Article also belongs_to a current_revision, which is the primary key of the Revision that is currently selected. Each Revision is never changed after being created.

When a user goes to edit an Article, I want to display a form that shows all the fields that are in revisions, pre-populated with that information from the current_revision. That's simple enough, but when the user goes to save, I want to compare each field to the value in the current_revision. If all of the fields are the same, I want to do nothing and discard the form post. However, if any of the fields are different, I want to create a new Revision instead of writing to the previous Revision.

How can I detect whether any field has changed except by manually hard-coding a test for each field of the Revision?

+2  A: 

There are built in methods for detecting changes in Active Record.

The API has good documentation on the tracking changes: http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html.

In your case, it should simply be a matter of detecting which fields have changed in the Article, and then creating a new Revision from that.

Something along the lines of:

article= Article.find(id)
article.attributes = params[:article]
if article.changed?  
  //new revision
end
Toby Hede
Thanks, I wasn't familiar with those methods.Is there a good way for detecting that certain fields weren't submitted (for example, the form has a checkbox for "Has extended info", and shows/removes rows with javascript accordingly) and using the absence of those fields in params to set those fields to nil?
WIlliam Jones