11

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.

4

2 回答 2

6

您可以使用 :foreign_key 来指定 mongodb 字段名称。

belongs_to :account, foreign_key: :ac

但是,如果要使用 account_id,则需要声明其别名:

alias :account_id :ac

或在 belongs_to 之前定义 account_id:

field :account_id, as: :ac
于 2013-09-13T08:45:08.270 回答
1

Mongoid 允许通过使用 'inverse_of' 为关系使用任意名称

如果不需要逆向,例如belongs_to 或has_and_belongs_to_many,请确保在关系上设置:inverse_of => nil。如果需要逆,很可能无法从关系的名称中找出逆,您需要在关系上明确告诉 Mongoid 逆是什么。

因此,要使用 'ac' 作为别名,必须添加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
于 2013-02-04T07:52:58.737 回答