Bruce Lin
Bruce Lin

Reputation: 2740

Mongoid has_and_belongs_to_many, inverse_of: :nil, store_as

In my code I have a user class:

class User
  include Mongoid::Document
  has_and_belongs_to_many :person_record_bookmarks, inverse_of: nil, :class_name => "PersonRecord"
end

now it will generate person_record_bookmarks_ids in my document. This name is too long, is there any way to store it as shorter name in the database? In embed documents we can use store_as:, but seems it doesn't work for references.

Upvotes: 0

Views: 714

Answers (1)

Enrique Fueyo
Enrique Fueyo

Reputation: 3488

foreign_key is what you are looking for

class User
  include Mongoid::Document
  has_and_belongs_to_many :person_record_bookmarks, inverse_of: nil, :class_name => "PersonRecord", foreign_key :shorter_name
end

then your user will be:

{...shorter_name:[ObjectId("..."),ObjectId("...")]...}

You can user user.shorter_name to retrieve the list of ids or user.person_record_bookmarks to retrieve all PersonRecordBookmarks.where({_id: {$in: shorter_name})

Upvotes: 3

Related Questions