alexs333
alexs333

Reputation: 12593

ActiveRecord STI Forreign Key Override for Associations

I have some inheritance modeled using STI. It has a base class, just like this:

class Tariff < ActiveRecord:Base
end

Then it has a couple of children:

def FlatRateTariff < Tariff
end

One of the classes has a has_many associations:

def TimeOfUseTariff < Tariff
  has_many :tariff_periods, :dependent => :destroy
end

Here is the TariffingPeriod class that I've specified in the association:

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

When in my controller or view i call @tariff.tariffing_periods ActiveRecord spits out something like this:

SELECT * FROM `tariffing_periods` WHERE (`tariffing_periods`.time_of_use_tariff_id = 13)

As you can see, I have the incorrect foreign key (time_of_use_tariff_id). Is there a way to override this foreign key somehow or force ActiveRecord to generate correct SQL? I have tried :foreign_key override in TariffingPeriod, but that doesn't help... Any ideas?

Upvotes: 3

Views: 1458

Answers (2)

user132447
user132447

Reputation: 1701

You'll want to specify the class_name as an option on the belongs_to side...

class TariffingPeriod < ActiveRecord::Base
  belongs_to :time_of_use_tariff, :foreign_key => :tariff_id, :class_name => "TimeOfUseTariff"
end

Upvotes: 0

Peter Brown
Peter Brown

Reputation: 51717

I'm guessing your fix was something along the lines of:

def TimeOfUseTariff < Tariff
  has_many :tariff_periods, :dependent => :destroy, :foreign_key => :tariff_id
end

Upvotes: 2

Related Questions