views:

422

answers:

1

Something I've always wondered about rails is the ability to pass extra data to find_or_create methods in rails. For example, I can't do the following

User.find_or_create_by_name('ceilingfish', :email => '[email protected]', :legs => true, :face => false)

I could do

u = User.find_or_create_by_name('ceilingfish')
u.update_attributes(:email => '[email protected]', :legs => true, :face => false)

But that's uglier, and also requires three queries. I suppose I could do

User.find_or_create_by_name_and_email_and_face_and_legs('ceilingfish','[email protected]',true, false)

But that kind of implies that I know what the values of email, legs and face are. Does anyone know if there's a really elegant way of doing this?

+4  A: 

Try this:

User.find_or_create_by_name(:name=>'ceilingfish', 
        :email => '[email protected]', :legs => true, :face => false)

When you have additional parameters to find_or_create_by_, you have to pass all the parameters as a hash.

KandadaBoggu
Wow that's awesome, thanks Kandada, the only quirk I have noticed is that if any of the attributes are invalid (say in the above example email had a validation pattern that checked for a proper tld), then none of the following attributes are set (so legs and face would still be nil)
Ceilingfish
@Ceilingfish: It's actually a bug that your first form doesn't work. http://rails.lighthouseapp.com/projects/8994/tickets/4457-find_or_create_by_foo-when-foo-is-protected-attribute
Marc-André Lafortune