1

我目前正在从 mongoid 2.0 迁移到 mongoid 3.0.5。我在对象中的关系之一是has_many_related. 如何将其迁移到 mongoid 3.0.5?我无法通过谷歌搜索或在 mongoid.org 和 two.mongoid.org 网站上找到任何文档。有没有我应该找的地方?

这是代码:

  has_many_related :food_review do
    def find_or_initialize_by_user_id(user_id)
      criteria.where(:user_id => user_id).first || build(:user_id => user_id)
    end
  end

谢谢!

4

2 回答 2

4

只需使用 has_many 而不是 has_many_related。

例如 :

class User
  include Mongoid::Document
  field :name, type: String
  field ...

  has_many :food_reviews

  def find_or_initialize_by_user_id(user_id)
    criteria.where(:user_id => user_id).first || build(:user_id => user_id)
  end
end

class FoodReview
  include Mongoid::Document
  field ...

  belongs_to :user
end

注意复数has_many :food_reviews和单数class FoodReview。如果您想引用单个评论,只需use has_one :food_review(参见引用 1-1

于 2012-09-12T19:51:15.697 回答
2

看mongoid 2.0的代码has_many_related只是has_many的一个别名:

➜  mongoid  git grep has_many_related
lib/ mongoid/relations/macros.rb:        alias :has_many_related :has_many

只需将其更改为 :has_many 并保持代码相同。在此处的 Mongoid 文档中有一个给 :has_many 的块示例

于 2012-09-12T16:46:06.483 回答