我知道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
我能看到的唯一的事情是,第二個例子中的命名讓人有點更有意義。
我知道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
我能看到的唯一的事情是,第二個例子中的命名讓人有點更有意義。
是的。
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語句當你查詢表時。
似乎很容易測試。 –