2014-01-28 50 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语句当你查询表时。

相关问题