Passing extra data to find_or_create

ruby-on-rails

Solution

Try this:

User.find_or_create_by_name(:name=>'ceilingfish', 
        :email => 'an_email@a.domain', :legs => true, :face => false)

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

Rails 4

  User.create_with(
    email: 'an_email@a.domain', 
    legs: true, face:false
  ).find_or_create_by(:name=>'ceilingfish')

Problem

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 => 'an_email@a.domain', :legs => true, :face => false) ``` I could do ``` u = User.find_or_create_by_name('ceilingfish') u.update_attributes(:email => 'an_email@a.domain', :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','an_email@a.domain',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?

Original source