别名Mongoid中的引用关系字段

Har*_*tty 11 mongoid ruby-on-rails-3

在下面的Mongoid模型中,我如何为belongs_to关系字段添加别名?

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
Run Code Online (Sandbox Code Playgroud)

我想将帐户ID存储在一个名为ac而不是的字段中account_id.

Hoa*_*yen 6

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

belongs_to :account, foreign_key: :ac
Run Code Online (Sandbox Code Playgroud)

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

alias :account_id :ac
Run Code Online (Sandbox Code Playgroud)

或者在belongs_to之前定义account_id:

field :account_id, as: :ac
Run Code Online (Sandbox Code Playgroud)


Den*_*hin 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
Run Code Online (Sandbox Code Playgroud)