What is the difference between t.belongs_to and t.references in rails?

廉价感情. 提交于 2019-11-28 15:42:03

问题


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

回答1:


Looking at the source code, they do the same exact thing -- belongs_to is an alias of reference:

  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

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 to references for other sorts of associations.



来源:https://stackoverflow.com/questions/7788188/what-is-the-difference-between-t-belongs-to-and-t-references-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!