2014-01-28 52 views
0

我知道belongs_to將外鍵放在聲明模型上,而has_one將其放在另一個模型上。這是否意味着這個例子沒有區別?一個模型上的has_one與另一個模型上的belongs_to有區別嗎?

class Category 
belongs_to :blog 
end 

class Blog 
end 

class Blog 
has_one :category 
end 

class Category 
end 

我能看到的唯一的事情是,第二個例子中的命名讓人有點更有意義。

+0

似乎很容易測試。 –

回答

1

不同之處在於數據庫,正如您所指出的那樣。 belongs_to參考必須包含該關聯的外鍵的模型。當使用has_one時,它會期望在相關模型上找到外鍵。

+0

是否有理由使用另一個,特別是如果它將是一個可選的關係? – jsurf

+0

如果一個人明顯是另一個物體的孩子,那麼我喜歡'belongs_to'。如果它們只是兄弟對象(例如不是子類),那麼'has_one'可能更有意義。 – CDub

2

是的。

belongs_to預計外鍵是其表,而has_one希望它是另:

# here the Category table will need to have a blog_id field 
class Category 
    belongs_to :blog 
end 

# the blog table won't need anything  
class Blog 
    has_one :category 
end 

has_one引擎蓋下是類似於has_many除了它增加了一個LIMIT 1子句的SQL語句當你查詢表時。

相關問題