has and belongs to many - How can I join the same 2 models twice in Rails? -
i have app country preferences. user have 2 types of country preferences - event , research. in future there may more. leaning more towards having 2 tables represent on using sti. i'm having bit of trouble configuring rails elegantly this. hack rather rails convention. want 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 "pseudo code" know how implement in rails?
i think you're going declaring them wrong, because should work properly. that's :through
directive for:
class user < activerecord::base has_many :event_countries has_many :countries_with_events, :through => :event_countries, :source => :country has_many :research_countries has_many :countries_with_researches, :through => :research_countries, :source => :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
a lot of awkwardness comes labels you've chosen tables. although they'd seem reasonable @ first glance, way use them ends making them difficult.
you might want call research_countries
user_research_countries
relationship name can user.research_countries
:through
:
class user < activerecord::base has_many :user_event_countries has_many :event_countries, :through => :user_event_countries, :source => :country has_many :user_research_countries has_many :research_countries, :through => :user_research_countries, :source => :country end class usereventcountry < activerecord::base belongs_to :country belongs_to :user end class userresearchcountry < activerecord::base belongs_to :country belongs_to :user end class country < activerecord::base # ... end
you can refactor further adding field user-country association table includes 1 or more flags, in case research or event or whatever require later:
class user < activerecord::base has_many :user_countries has_many :event_countries, :through => :user_countries, :source => :country, :conditions => { :event => true } has_many :research_countries, :through => :user_countries, :source => :country, :conditions => { :research => true } end class usercountry < activerecord::base belongs_to :country belongs_to :user # * column :event, :boolean # * column :research, :boolean end class country < activerecord::base # ... end
Comments
Post a Comment