Mongoid belongs_to indicate foreign_key

I would like to establish a relationship between two Mongolian models with has_many and belongs_to and specify a foreign key, for example:

class Author
  include Mongoid::Document

  field :serial_num, :type => Integer
  field :author_name, :type => String

  has_many :books
end

class Book
  include Mongoid::Document

  field :serial_num, :type => Integer
  field :book_name, :type => String

  belongs_to :author, foreign_key: 'serial_num'
end

This does not work. My IRB output:

irb :001> b = Book.first
=> #<Book _id: 1, serial_num: "12345", book_name: 'something', author_id: nil>
irb :002> b.author
=> nil

Is it possible to specify 'serial_num' as a foreign key for this relationship, or am I stuck with author_id?

Many thanks.

+4
source share
1 answer

I know this is an old post, but I assume that it is related to the type of field that the foreign key is stored. If it is not a BSON ObjectId, it may not return anything.

0
source

All Articles