2013-07-04 87 views
4

Mongoid中兩個模型之間的關係中是否明確需要外鍵?例如。外鍵和Mongoid

class User 
    include Mongoid::Document 
    has_many :posts 
end 

class Post 
    include Mongoid::Document 
    belongs_to :user 
    # Is this necessary below? 
    field :user_id, type: Integer 
end 

Mongoid網站上的文檔在討論關係時沒有指出任何字段的聲明,這就是我爲什麼要問的原因。

回答

7

不,通常不需要分開的外鍵字段聲明。 Mongoid將隱式地在任何需要它的文檔上創建user_id字段。它遵循與ActiveRecord相同的外鍵命名約定。

如果這些約定不適合您的模型(例如,如果您有兩個關聯到同一個類),那麼您可以重寫外鍵名稱。例如

belongs_to :user, foreign_key: :friend_id 

再次,這是非常相同的ActiveRecord(但沒有遷移當然)。

0

型號region.rb

class Region 
    ... 
    field :title 
    has_many :users 
    ... 

型號user.rb

class User 
    ... 
    belongs_to :reg, class_name: "Region", foreign_key: :reg_id 
    ... 

您現在可以使用regionuser如下user.reg,例如:

= user.reg.title