First_or_create匹配更新?

时间:2013-05-01 18:25:46

标签: ruby-on-rails activerecord associations

我非常喜欢first_or_create方法:

# Find the first user named Scarlett or create a new one with a particular last name.
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

我想知道如果不存在或不同,我还可以使用last_name'Johannson'更新用户。寻找最简洁的方法。与上述类似的单衬里将是理想的。

一种可能的方法是using first_or_initialize combined with update_attributes。我对这种方法唯一关注的是,即使所提供的字段与100%匹配,它也会运行更新。

2 个答案:

答案 0 :(得分:14)

Zaid非常接近正确。

User.where(first_name: 'Scarlett').first_or_create.update(last_name: 'Johansson')

这里有详细的差异。 (注意:这适用于Rails 3+和Rails 4 +)

  1. first_or_createfirst_or_initialize之间的区别在于_initialize使用.new方法并且不保存记录与.create和自动保存它。

  2. .update.update_attributes.update_attributes之间的差异是您在拥有值的哈希值时使用的值,通常来自表单提交,如{{1} }。另一方面,params可让您轻松指定上面.update等所示的每个属性。

  3. 就像Zaid所说,但它适用于(field_column: value, field_column2: value2).update,rails数据库更新&#34; ...只有在有更改的情况下才会命中数据库... &#34;

答案 1 :(得分:6)

first_or_initialize

update_attributes应该没问题。 Rails非常智能,只有在进行了更改时才会update_attributes命中数据库(您应该可以使用控制台/日志自行确认)。