【问题标题】:Rails Single-Table Inheritance (STI): dependencies on the derived modelsRails 单表继承 (STI):对派生模型的依赖
【发布时间】:2011-11-07 04:06:57
【问题描述】:

我即将在我的 Rails 2.3 应用程序中使用 STI。

我已经按照以下方式对其进行了建模:

基类:

class Tariff < ActiveRecord::Base
  def self.inherited(child)
    child.instance_eval do
      def model_name
        Tariff.model_name
      end
    end
    super
  end

  def self.select_options
    descendants.map { |c| c.to_s }.sort
  end
end

它的子类:

class FlatRateTariff < Tariff
end

class TimeOfUseTariff  < Tariff
  has_many :tariffing_periods, :dependent => :destroy
  accepts_nested_attributes_for :tariffing_periods, :allow_destroy => true
end

当我尝试创建 form_for :tariff 时,我得到了一个 未定义的方法 `tariffing_periods' for Tariff。我应该如何对这种情况进行建模?我应该把 has_many 关联放在父类上吗?

【问题讨论】:

    标签: ruby-on-rails sti


    【解决方案1】:

    STI 通常在 Rails 中这样完成:

    class Tariff < ActiveRecord::Base
    end
    
    class FlatRateTariff < Tariff
    end
    
    class TimeOfUseTariff < Tariff
    end
    

    确保 Tariff 表有一个属性 type:string - 这是 ActiveRecord 存储类名的地方

    你不需要这个:(你可以检查 .class

     def self.inherited(child)
        child.instance_eval do
          def model_name
            Tariff.model_name
          end
        end
        super
      end
    

    这里有更多信息:

    Agile Web Development with Rails 第 3 版中的第 373 页

    或: http://my.safaribooksonline.com/book/web-development/ruby/9780132480345/advanced-active-record/ch09lev1sec5

    【讨论】:

    • 感谢您的指点,我依靠 IDE 来纠正这些问题。然而,性传播感染问题仍然存在......
    • 是的,我确实有原因的类型属性。我确实删除了“继承的”辅助方法,谢谢。然而,当我执行 form_for :tariff 时,它仍然抱怨未定义的 taxing_periods 方法,我在 Tariff 的子类中使用了该方法......这是有道理的,因为 ActiveRecord 还不知道我正在创建 Tariff 的哪个子类。然而我仍然不知道该怎么做......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2015-06-23
    相关资源
    最近更新 更多