Reputation: 759
I'm on rails 4 and I couldn't figure out how to join two models twice in rails. I found an answer to my problem here but it's an old one, here's what it says:
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
I found this solution interesting as I only need one join table for UserCountries, however it doesn't seem to work in rails 4 (the conditions method has been deprecated in rails 4.0), so my question is simply : how would you do this in rails 4.0 ?
Upvotes: 1
Views: 186
Reputation: 10796
The solution you mention is still valid, you just need to change the conditions part to adopt the new Rails 4 convention (see similar question here):
class User < ActiveRecord::Base
has_many :user_countries
has_many :event_countries,
-> { where(user_countries: {:event => true}) },
:through => :user_countries,
:source => :country
has_many :research_countries,
-> { where(user_countries: {:research => true}) },
:through => :user_countries
:source => :country
end
class UserCountry < ActiveRecord::Base
belongs_to :country
belongs_to :user
end
class Country < ActiveRecord::Base
# ...
end
Upvotes: 2