Boaz
Boaz

Reputation: 5084

multiple belongs_to in mongoid

The models:

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

Now I want to have the Writers name displayed in the post view. something like:

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

default scaffold controller for now.

The error I'm getting:
undefined method `name' for nil:NilClass

When I try it in rails console:
ccc=Post.find_by(name:"bla bla")
ccc.writer >>> nil
ccc.writer_id >>> "5284c0bc1d41c837c1000001"

The reviewer on the other hand is A OK:
ccc.reviewer - returns a perfect object

What am I doing wrong?

Upvotes: 0

Views: 945

Answers (1)

Chen Fisher
Chen Fisher

Reputation: 1455

Boaz,

When you say

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

I suspect you create a Post while referencing a User instead of a Writer

Mongoid adds a _type field to your document when you use inheritance and every query has a "hidden" _type selector.

So when you do ccc.writer Mongoid adds a _type == Writer to the query so you get nil because the ID you have is actually a _type=User

Upvotes: 1

Related Questions