我知道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语句当你查询表时。
似乎很容易测试。 –