我怎么能用外键和主键的差异来操纵HasMany关系

时间:2016-02-25 02:28:01

标签: ruby-on-rails-4 mongoid

我有User model and Comment model,每个用户都有很多评论

要查找评论的所有者,您需要找到与评论的author_id匹配的用户uid。

我怎样才能在Mongoid中设置has_many关系?

是否可以避免N+1 query,当我先加载所有注释然后为每条注释添加user.name?感谢

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps
  belongs_to :user #, foreign_key: :uid ????
  field :post_id, type: String
  field :author_id, type: Integer
end


class User
  include Mongoid::Document
  include Mongoid::Timestamps
  has_many :comments
  field :uid, type: Integer
  field :name, type: String
end

0 个答案:

没有答案