Difference between two different ways of using first_or_create in ActiveRecord

I'm totally new to ActiveRecord, so this might be a dumb question: I wrote my method like this:

sample_organizations = [ '37 Signals', 'Fog Creek'] 
sample_organizations.each { |item|
    Organization.first_or_create(
        name: item,
        time_zone: 'Central'
    )
  }

      

and it didn't work, I was hoping it would go through my array of organizations and insert them all into the DB, but it just inserted one first row.

Then someone suggested changing it like this and THIS worked, but I was wondering if anyone could explain what was wrong in the first method so I could find out what I was doing / taking wrong.

so this worked:

   sample_organizations = [ '37 Signals', 'Fog Creek'] 
    sample_organizations.each { |item|
    Organization.where(name: item).where(time_zone: 'Central').first_or_create
      }

      

+3


source to share


2 answers


There are actually two methods:, find_or_create_by

add one column and set a set of attributes.

So, for example, you can write:

find_or_create_by_name('Willy', time_zone: 'UTC')

      

Second first_or_create

, and it works the way it was suggested to you (your second solution) (see documentation ).

It was suggested to introduce a method find_or_create

that takes a hash, but this resulted in first_or_create

. (see discussion here.)



Note that both are also well explained in the relevant guide rails .

[UPDATE 2014-06-30] Please note that currently the notation has been changed, now we have to write

Organization.find_or_create_by(name: '37 signals') do |organisation|
  organisation.time_zone = 'Central'
end

      

which will try to find the organization by name, and if not found, use the block to create the organization. Note: the block is executed only if the organization does not exist!

+5


source


It should look like this:



sample_organizations.each { |item|
  Organization.find_or_create_by_name(item, time_zone: 'Central')
}

      

+4


source







All Articles