Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing a referenced relationship field in Mongoid

In the Mongoid model below, how do I alias the belongs_to relationship field?

class Contact
  field :nm, :as => :name, :type => String # field aliasing
  embeds_one :address, :store_as => :ad  # embedded document aliasing
  belongs_to :account # referenced relation doesn't support store_as
end

I want to store the account id in a field called ac instead of account_id.

like image 928
Harish Shetty Avatar asked Feb 01 '13 22:02

Harish Shetty


2 Answers

You can use :foreign_key to specify the mongodb field name.

belongs_to :account, foreign_key: :ac

However, if you want to use account_id, you need to declare its alias:

alias :account_id :ac

or defining account_id before belongs_to:

field :account_id, as: :ac
like image 71
Hoan Nguyen Avatar answered Oct 23 '22 16:10

Hoan Nguyen


Mongoid allows to use arbitrary name for a relationship by using of 'inverse_of'

If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.

So, for use 'ac' as an alias it's necessary to add inverse_of:

class Contact
  field :nm, :as => :name, :type => String # field aliasing
  embeds_one :address, :store_as => :ad  # embedded document aliasing
  belongs_to :ac, class_name: 'Account', inverse_of: :contact
end

class Account
  has_one :contact, class_name: 'Contact', inverse_of: :ac
end
like image 39
Denis Kreshikhin Avatar answered Oct 23 '22 16:10

Denis Kreshikhin