我如何级联保存与mongoid的has_and_belongs_to_many关系?

时间:2012-08-30 22:49:07

标签: ruby mongoid

我有一个标签和一个问题类。

class Question
  include Mongoid::Document
  include Mongoid::Timestamps
  identity type: String
  has_and_belongs_to_many :tags # Refer to tag_ids
end

class Tag
  include Mongoid::Document
  identity type: String    
  has_and_belongs_to_many :questions
end

但是,当我执行以下操作时,标签不会保存:

t = Tag.new(id: "politics")
q = Question.new({tags: [t]})
q.save!

但是,当我这样做时会创建标签:

Question.create!({tags: [Tag.new(id: "politics")]})

1 个答案:

答案 0 :(得分:1)

如果我执行以下操作,那么它将正常工作:

has_and_belongs_to_many :tags, autosave: true # Refer to tag_ids