Mongoid相当于create_with

时间:2015-04-10 14:22:52

标签: ruby-on-rails ruby mongodb mongoid

是否有等效的Active Records Model.create_with来传递Mongoid中查找参数的创建参数?

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

我发现自己使用了一个笨重的解决方法:

user = User.find_or_initialze_by(first_name: 'Scarlett')
user.update(last_name: 'Johansson') if user.new_record?

1 个答案:

答案 0 :(得分:4)

Mongoid的find_or_create_by采用一个可选块,仅在需要创建时使用。文档并未明确说明此行为,但如果您检查代码,则会看到find_or_create_by最终会调用此find_or方法:

def find_or(method, attrs = {}, &block)
  where(attrs).first || send(method, attrs, &block)
end
如果method找到了您要查找的文档,那么:createblock并且where不会被使用。

这意味着您可以说:

user = User.find_or_create_by(first_name: 'Scarlett') do |user|
  user.last_name = 'Johansson'
end

获得你想要的效果。

大概这个“create一半使用块”行为应该是显而易见的,因为create需要一个块来初始化对象,但find没有。

如果您对此未记录的行为感到偏执,可以在规范中加入检查,以便至少知道升级何时会破坏它。