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

What is the difference between t.references and t.belongs_to ? Why do we have these two different words? It seems to me that they are doing the same? I tried a search on Google, but did not find an 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 
+109
ruby-on-rails ruby-on-rails-3 rails-migrations
Oct 16 2018-11-11T00:
source share
1 answer

Looking at the source code , they do the same - belongs_to is a reference alias:

  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 to make your code more readable - it's nice to be able to carry belongs_to into your migrations when necessary, and stick to references for other kinds of associations.

+143
Oct 17 2018-11-11T00:
source share



All Articles