mongoid中的多个belongs_to

时间:2013-11-27 17:04:31

标签: ruby-on-rails mongoid

模特:

class Post
  include Mongoid::Document
  ...
  belongs_to :writer, class_name: 'Writer', inverse_of: :posts
  belongs_to :reviewer, class_name: 'User', inverse_of: :reviewed_posts
end

class User
  include Mongoid::Document
  field :name,   :type => String
  ...
  has_many :reviewed_posts, class_name: 'Post', inverse_of: reviewer
end

class Writer < User
  has_many :posts, class_name: 'Post', inverse_of: :writer
end

现在我希望在帖子视图中显示作家姓名。 类似的东西:

<div>
  Writer: <%= @post.writer.name %>
</div>

现在默认的脚手架控制器。

我得到的错误:
undefined method `name' for nil:NilClass

当我在rails console中尝试时:
ccc=Post.find_by(name:"bla bla")
ccc.writer >>> nil
ccc.writer_id >>> "5284c0bc1d41c837c1000001"

另一方面,评论者是A OK:
ccc.reviewer - returns a perfect object

我做错了什么?

1 个答案:

答案 0 :(得分:1)

波阿斯,

当你说

ccc.writer_id >>> "5284c0bc1d41c837c1000001"
ccc.writer >>> nil

我怀疑您在引用Post而不是User

时创建Writer 当您使用继承并且每个查询都有一个“隐藏的”Mongoid选择器时,

_type会在您的文档中添加_type字段。

所以当你这样做的时候 ccc.writer Mongoid会在查询中添加_type == Writer,因此您获得nil,因为您拥有的ID实际上是_type=User