简体   繁体   中英

How to join the same 2 models twice in Rails 4.0?

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM