Archive for May, 2008

Find_Or_Create

One of my very favorite rails methods is find_or_create. You can turn this tedious code:

review = Review.find_by_url(sitename)
if review.nil?
review = Review.new
review.url = sitename
review.staff_id = staff.id
review.save
end

Into this clean one liner:

Review.find_or_create_by_url(sitename, {:staff_id => staff.id})

The has_many :through blog has a great rundown on dynamic finders that I found really useful.

One point that got missed is that like the create method, find_or_create will autosave the new object to the database. This is unlike the new method which doesn’t create a new object in the database but rather creates a new object. Which of course means that you’ll need the save method to ensure your data gets back to the db. In this case, you may want to use find_or_initialize.

If you want to create a new object in the DB in one step (if doesn’t exist already), find_or_create is a great tool.

4 comments May 19th, 2008


RSS Berkman Gender & Tech

RSS Tweets

Tags

Meta