rails中的t.belongs_to和t.references有什么区别?

t.referencest.belongs_to什么t.belongs_to ? 为什么我们有这两个不同的单词? 在我看来他们做同样的事情? 尝试了一些谷歌search,但没有find解释。

 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 

看看源代码 ,他们做同样的事情 – 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其他types的关联。