I have an app with country preferences. A user will have 2 types of country preferences – event and research. In the future there may be more. I was leaning more towards having 2 tables to represent this over using STI. I’m having a bit of trouble configuring Rails elegantly to do this. I could hack it but I would rather do this by Rails convention. What I want is something like this:
class User < ActiveRecord::Base
has_many event_countries, :through => :event_countries, :class_name => 'Country'
has_many research_countries, :through => :research_countries, :class_name => 'Country'
end
class EventCountry < ActiveRecord::Base
belongs_to :country
belongs_to :user
end
class ResearchCountry < ActiveRecord::Base
belongs_to :country
belongs_to :user
end
class Country < ActiveRecord::Base
...
end
This doesn’t work though. Given this “pseudo code” does anyone know how to actually implement this in Rails?
I think you’re going about declaring them wrong, because this should work properly. That’s what the
:throughdirective is for:A lot of the awkwardness comes from the labels you’ve chosen for the tables. Although they’d seem reasonable at first glance, the way you use them ends up making them difficult.
You might want to call
research_countriessomething likeuser_research_countriesso that the relationship name can beuser.research_countriesas the:through:You can refactor this even further by adding a field to the user-country association table that includes one or more flags, which in this case would be research or event or whatever you require later: