如何将元素添加到 mongoid 模型的 embeds_many 字段

How to add element to embeds_many field of mongoid model

我在模型(mongoid)中有 embeds_many 字段 :items

class Course
  embeds_many :items

  def create_item
    item = Item.new
    update_attributes items, items | [item]
  end
end

...

c = Course.new
item = c.create_item

:items 中添加新元素的正确方法是什么?我尝试使用 update_attributes items, items | [item] 但我认为这是丑陋的方法。

embeds_many 支持 ActiveRecord 的 has_many 所做的常用方法集,因此您可以这样说:

def create_item
  items.create(args)
end

就像您使用 AR has_many