rails 中的 t.belongs_to 和 t.references 有什么区别? [英] What is the difference between t.belongs_to and t.references in rails?

查看:56
本文介绍了rails 中的 t.belongs_to 和 t.references 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

t.referencest.belongs_to 有什么区别?为什么我们有这两个不同的词?在我看来他们做同样的事情?尝试了一些 Google 搜索,但没有找到任何解释.

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

推荐答案

源代码,它们做同样的事情——belongs_toreference 的别名:

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

这只是让你的代码更具可读性的一种方式——能够在适当的时候将 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.

这篇关于rails 中的 t.belongs_to 和 t.references 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆