Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Jan 20 ’10

Find or Create an object in one command

The find_or_create_by_ dynamic finder will return the object if it already exists and otherwise creates it, then returns it:

# No 'Summer' tag exists
Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")

# Now the 'Summer' tag does exist
Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")

There’s also a find_or_initialize_by finder if you want to return a new record without saving it first:

# No 'Winter' tag exists
winter = Tag.find_or_initialize_by_name("Winter")
winter.new_record? # true

Everything taken from the Rails API.

12 notes 0 comments

  1. curtisgwapo reblogged this from rubyquicktips
  2. rubyquicktips posted this


You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus