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
.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With