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

后端 未结 1 1913
南方客
南方客 2020-12-23 00:14

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? T

1条回答
  •  独厮守ぢ
    2020-12-23 00:44

    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.

    0 讨论(0)
提交回复
热议问题