Tor*_*den 117 ruby-on-rails rails-migrations
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
Run Code Online (Sandbox Code Playgroud)
muf*_*sta 152
查看源代码,他们做同样的事情 - 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
Run Code Online (Sandbox Code Playgroud)
这只是让您的代码更具可读性的一种方式 - 能够belongs_to在适当的时候放入您的迁移并且坚持references其他类型的关联是很好的.
| 归档时间: |
|
| 查看次数: |
24789 次 |
| 最近记录: |