part of the family
beyond corporate purpose

Find or create with hash attributes

04 Sep 2009

Dynamic finders in Rails, represent some the ‘magic’ we’ve all gotten used to. One can use these dynamic finders to create or initialize a new object when it doesn’t already exist.

# Find a user by screen_name_
user = User.find_by_screen_name("atog")  

# So instead of ...
user = User.find_by_screen_name("atog")  
unless user  
  user = User.create(:name => "atog")  

# ... you can  
user = User.find_or_create_by_screen_name("atog")  

It gets even better. By passing a hash to the finder you can initialize or create a new object with all the values while only the attribute named in the finder will be used to find the object.

user = User.find_or_create_by_screen_name(
		:screen_name => "atog", 
		:name => "Koen Van der Auwera")
blog comments powered by Disqus