簡體   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