gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:37:02 26 4
gpt4 key购买 nike

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

最佳答案

查看the source code ,它们做同样的事情 - belongs_toreference 的别名:

  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 来获取其他内容,这很好。各种关联。

关于ruby-on-rails - Rails 中的 t.belongs_to 和 t.references 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7788188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com