简体   繁体   English

在ActiveRecord中使用first_or_create的两种不同方式之间的差异

[英]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: 我是ActiveRecord的新手,所以这可能是一个愚蠢的问题:我写的方法是这样的:

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. 实际上,有两种方法: find_or_create_by ,添加一列并给出一组属性。

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). 第二个是first_or_create ,它按照你的建议工作(你的第二个解决方案)(参见文档 )。

There was a suggestion to introduce the find_or_create method, which accepts a hash, but that resulted in the first_or_create . 有人建议引入find_or_create方法,该方法接受哈希,但结果是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 [更新2014-06-30]请注意,目前符号已经更改,我们现在应该写

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')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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