如何在Rails 4.0中两次加入相同的2个模型?

时间:2014-12-15 20:46:45

标签: ruby-on-rails ruby-on-rails-4 activerecord

我在轨道4上,我无法弄清楚如何在轨道中连接两个模型两次。我找到了an answer to my problem here,但它是旧的,这就是它所说的:

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

我发现这个解决方案很有意思,因为我只需要一个UserCountries连接表,但它似乎不能在rails 4(the conditions method has been deprecated in rails 4.0)中工作,所以我的问题很简单:你将如何在rails中执行此操作4.0?

1 个答案:

答案 0 :(得分:2)

您提到的解决方案仍然有效,您只需要更改条件部分以采用新的Rails 4约定(请参阅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