繁体   English   中英

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

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

我在轨道4上,我不知道如何在轨道上两次加入两个模型。 我在这里找到了解决问题的答案,但这是一个古老的答案,它的含义是:

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中不起作用( 条件方法在rails 4.0中已弃用 ),所以我的问题很简单:您将如何在中执行此操作导轨4.0?

您提到的解决方案仍然有效,您只需要更改条件部分即可采用新的Rails 4约定(请参见此处的类似问题 ):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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