[英]Should we use the abstracted rails polymorphic migration syntax?
有兩種方法可以在Rails中編寫多態遷移。 通常,我這樣做是:
class CreateFeatures < ActiveRecord::Migration
def change
create_table :features do |t|
t.integer :featureable_id
t.string :featurable_type
t.timestamps
end
end
end
但是,我們也可以這樣做:
class CreateFeatures < ActiveRecord::Migration
def change
create_table :features do |t|
t.references :featureable, :polymorphic => true
t.timestamps
end
end
end
出於所有實際目的,兩者是相同的。 我的問題: 一個比另一個好嗎? 有更好的未來可維護性嗎?
僅當以下兩項發生更改時,這才可能成為問題:
只是想知道是否有偏好,或者是“ Meh,這兩種方式都沒有關系”
對於通過遷移生成所有表的全軌應用程序,功能上沒有區別。
這是參考代碼:
def references(*args)
options = args.extract_options!
polymorphic = options.delete(:polymorphic)
args.each do |col|
@base.add_column(@table_name, "#{col}_id", :integer, options)
@base.add_column(@table_name, "#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) unless polymorphic.nil?
end
end
一切都很好,但是如果您在引用表上的外鍵不是_id,則方法一是唯一的選擇。
引用只會為您節省一行代碼...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.