我非常喜欢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%匹配,它也会运行更新。
答案 0 :(得分:14)
Zaid非常接近正确。
User.where(first_name: 'Scarlett').first_or_create.update(last_name: 'Johansson')
这里有详细的差异。 (注意:这适用于Rails 3+和Rails 4 +)
first_or_create
与first_or_initialize
之间的区别在于_initialize
使用.new
方法并且不保存记录与.create
和自动保存它。
.update
与.update_attributes
,.update_attributes
之间的差异是您在拥有值的哈希值时使用的值,通常来自表单提交,如{{1} }。另一方面,params
可让您轻松指定上面.update
等所示的每个属性。
就像Zaid所说,但它适用于(field_column: value, field_column2: value2)
和.update
,rails数据库更新&#34; ...只有在有更改的情况下才会命中数据库... &#34;
答案 1 :(得分:6)
first_or_initialize
的 update_attributes
应该没问题。 Rails非常智能,只有在进行了更改时才会update_attributes
命中数据库(您应该可以使用控制台/日志自行确认)。