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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7788188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:10:53  来源:igfitidea点击:

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

ruby-on-railsrails-migrations

提问by Tornskaden

What is the difference between t.referencesand 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.

t.references和 和有t.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

回答by muffinista

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

查看源代码,他们做同样的事情——belongs_to是一个别名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_toin your migrations when appropriate, and stick to referencesfor other sorts of associations.

这只是使您的代码更具可读性的一种方式——能够belongs_to在适当的时候进行迁移并坚持references其他类型的关联是很好的。