Rails 中的 t.belongs_to 和 t.references 有什么区别?
t.references
和 t.belongs_to
之间有什么区别? 为什么我们有这两个不同的词?在我看来他们做同样的事情? 尝试了一些谷歌搜索,但没有找到解释。
class CreateFoos < ActiveRecord::Migration
def change
create_table :foos do |t|
t.references :bar
t.belongs_to :baz
# The two above seems to give similar results
t.belongs_to :fooable, :polymorphic => true
# I have not tried polymorphic with t.references
t.timestamps
end
end
end
What is the difference between t.references
and t.belongs_to
?
Why are we having those two different words? It seems to me they do the same thing?
Tried some Google search, but find no explanation.
class CreateFoos < ActiveRecord::Migration
def change
create_table :foos do |t|
t.references :bar
t.belongs_to :baz
# The two above seems to give similar results
t.belongs_to :fooable, :polymorphic => true
# I have not tried polymorphic with t.references
t.timestamps
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看源代码,他们做同样的事情——
belongs_to
是reference
的别名:这只是使代码更具可读性的一种方式 - 能够将
belongs_to
放入其中真是太好了在适当的时候进行迁移,并坚持其他类型关联的引用
。Looking at the source code, they do the same exact thing --
belongs_to
is an alias ofreference
:This is just a way of making your code more readable -- it's nice to be able to put
belongs_to
in your migrations when appropriate, and stick toreferences
for other sorts of associations.