简体   繁体   中英

Difference between two different ways of using first_or_create in ActiveRecord

I am totally new to ActiveRecord so this maybe a dumb question: I had written 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 will iterate through my array of organiations and will insert them all in the DB, but it just inserted one first row.

Then someone suggested to change it like this and THIS one worked, But I was wondering if someone can explain what was wrong in the first method so I can learn what was I doing/assuming wrong.

so this one worked:

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

Actually, there are two methods: find_or_create_by , add one column and give a set of attributes.

So, for example you can write:

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

The second is first_or_create , and that works as you were suggested (your second solution) (see the documentation as well).

There was a suggestion to introduce the find_or_create method, which accepts a hash, but that resulted in the first_or_create . (see discussion here).

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

[UPDATE 2014-06-30] Note that currently the notation has been changed, we should now write

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

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

It should be like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM