2013-04-07 26 views
1

之間的區別以下三種情況有什麼區別?has_many,belong_to和

#Case 1 
class User < ActiveRecord::Base 
    has_many :comment 
end 

class Comment < ActiveRecord::Base 
    belong_to :user 
end 

情況1具有has_many和belong_to。

#Case 2 
class User < ActiveRecord::Base 
    has_many :comment 
end 

class Comment < ActiveRecord::Base 
end 

情況2只有has_many。

#Case 3 
class User < ActiveRecord::Base 
end 

class Comment < ActiveRecord::Base 
    belong_to :user 
end 

案例3只有belongs_to。

既然has_many和belong_to代表一對多關係,那麼我們如何決定我們應該使用哪三個?

+0

就像一個說明,你的'has_many'應該是複數:'has_many:comments' – 2013-04-07 00:57:38

+0

什麼時候應該使用單數和複數? – ZeroNegOne 2013-04-07 01:01:15

+0

'has_many' =複數(many),'belongs_to' =單數(僅屬於1)。我只注意到你的'belongs_to'也是錯的,你遺漏了一個「s」。另外,如果您使用'has_one',則需要使用單數。 – 2013-04-07 01:03:02

回答

2

它們需要相同的數據庫模式。區別僅在於爲您定義了哪些方法。

當您添加has_many :commentsUser,您將獲得指user.comments的能力,所以很容易地找到一個特定的用戶對象的意見(與user.comments.build創建新的,等等)。

當您將belongs_to :user添加到Comment時,您將獲得引用comment.user的能力,因此找到特定評論對象所屬的用戶。

這些調用只是簡單地創建便捷的方法供您在操作模型對象時使用。我會建議使用這兩種方法,因爲您可能會想要使用這兩種方法,而且閱讀代碼的人員之間的關係更加清晰。

+0

它如何影響服務器工作負載?使用兩者是否會增加開銷? – ZeroNegOne 2013-04-07 00:52:58

+1

它不明顯影響服務器的工作量。數據庫模式完全相同,因此您發出的查詢是相同的。 – 2013-04-07 00:53:59