Recent Posts by blinkless

Subscribe to Recent Posts by blinkless 2 posts found

Aug 31, 2007
Avatar blinkless 2 posts

Topic: General Ruby/Rails Discussion / associations and join tables

Thanks Ben! That worked perfectly after one change. All I had to do was define a :source option.

class Country < ActiveRecord::Base
    has_many :carrier_countries
    has_many :carriers, :through => :carrier_countries
    has_many :major_carriers, :through => :carrier_countries, :source => :carrier, :conditions => 'major = 1'
end
Here’s more info on the :source option:
:source: Specifies the source association name used by has_many :through queries. Only use it if the name cannot be inferred from the association.
 
Aug 30, 2007
Avatar blinkless 2 posts

Topic: General Ruby/Rails Discussion / associations and join tables

I’m having a hard time wrapping my head around an association problem.

I have 2 classes with a many to many relationship: Carrier and Country.

I created a join table model (CarrierCountry) and defined a through association that gives me @carrier.countries and @country.carriers and this works great.

My problem is I’ve added a field to the CarrierCountry model that defines if the Carrier is a major carrier for that Country. I’m trying to define an association that will let me do something like this: @country.major_carriers which should return all the Country’s major Carriers.

I can’t figure out where to define the association or if I took a wrong turn somewhere.

Code:
class Country < ActiveRecord::Base
    has_many :carrier_countries
    has_many :carriers, :through => :carrier_countries
end

class Carrier < ActiveRecord::Base
    has_many :carrier_countries
    has_many :countries, :through => :carrier_countries
end

class CarrierCountry < ActiveRecord::Base
    belongs_to :carrier
    belongs_to :country
end