开发者

How to handle revisions to a Wiki with ActiveRecord?

开发者 https://www.devze.com 2022-12-18 03:12 出处:网络
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 k

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 writin开发者_如何转开发g 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?


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

The API has good documentation on the tracking changes: http://ar.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
0

精彩评论

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