【发布时间】:2013-05-01 18:25:46
【问题描述】:
我真的很喜欢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'>
我想知道如果姓氏“Johannson”不存在或不同,我如何也可以更新用户。寻找最简单的方法。与上述类似的单衬里将是理想的。
一种可能的方法是using first_or_initialize combined with update_attributes。我对这种方法的唯一担忧是,即使提供的字段 100% 匹配,它也会运行更新。
【问题讨论】:
标签: ruby-on-rails activerecord associations