在 Rail 中,t.properties_to 和 t.reference 之间的区别是什么?

t.referencest.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
34821 次浏览

看看 源代码,他们做同样的事情—— belongs_toreference的别名:

  def references(*args)
options = args.extract_options!
polymorphic = options.delete(:polymorphic)
args.each do |col|
column("#{col}_id", :integer, options)
column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) unless polymorphic.nil?
end
end
alias :belongs_to :references

这只是使代码更易读的一种方法——能够在适当的时候将 belongs_to放入迁移中,并坚持使用 references进行其他类型的关联是很好的。