我有一些使用 STI 建模的继承。它有一个基类,就像这样:
class Tariff < ActiveRecord:Base
end
然后它有几个 child :
def FlatRateTariff < Tariff
end
其中一个类具有 has_many 关联:
def TimeOfUseTariff < Tariff
has_many :tariff_periods, :dependent => :destroy
end
这是我在关联中指定的 TariffingPeriod 类:
class TariffingPeriod < ActiveRecord::Base
belongs_to :time_of_use_tariff, :foreign_key => :tariff_id
# i've also tried :belongs_to :tariff, :foreign_key => :tariff_id
alias_attribute :time_of_use_tariff_id, :tariff_id # i've tried that just in case....
end
当我在我的 Controller 或 View 中调用 @tariff.tariffing_periods 时,ActiveRecord 会输出如下内容:
SELECT * FROM `tariffing_periods` WHERE (`tariffing_periods`.time_of_use_tariff_id = 13)
如您所见,我的外键 (time_of_use_tariff_id) 不正确。有没有办法以某种方式覆盖这个外键或强制 ActiveRecord 生成正确的 SQL?我在 TariffingPeriod 中尝试过 :foreign_key 覆盖,但这没有帮助...有什么想法吗?
最佳答案
我猜你的解决方法是:
def TimeOfUseTariff < Tariff
has_many :tariff_periods, :dependent => :destroy, :foreign_key => :tariff_id
end
关于ruby-on-rails - 关联的 ActiveRecord STI 外键覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8290907/