簡體   English   中英

我們應該使用抽象的rails多態遷移語法嗎?

[英]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

出於所有實際目的,兩者是相同的。 我的問題: 一個比另一個好嗎? 有更好的未來可維護性嗎?

僅當以下兩項發生更改時,這才可能成為問題:

  1. 多態抽象版本(版本2)消失或語法更改
  2. 處理多態關系(使用id和type)的方法發生變化-不太可能

只是想知道是否有偏好,或者是“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM