1

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 ?

Community
  • 1
  • 1
Badr Tazi
  • 749
  • 1
  • 6
  • 20

1 Answers1

2

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
Community
  • 1
  • 1
dgilperez
  • 10,716
  • 8
  • 68
  • 96
  • Thanks a lot for your answer however it looks like it tried to get the event column in the countries table: SQLite3::SQLException: no such column: countries.event: SELECT "countries".* FROM "countries" INNER JOIN "user_countries" ON "countries"."id" = "user_countries"."country_id" WHERE "countries"."event" = 't' AND "user_countries"."user_id" = ? – Badr Tazi Dec 15 '14 at 22:11
  • Indeed there are two things missing in your answer: - -> { where(user_countries: { event: true } } - :source => country – Badr Tazi Dec 15 '14 at 22:22
  • This is working: 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 You can edit so that I can accept it :) – Badr Tazi Dec 15 '14 at 22:25
  • @Badoo thanks for testing it, I wrote it from the top of my head. Code fixed. Glad to help! – dgilperez Dec 16 '14 at 12:47