[英]How do I query belongs_to through a HABTM in Rails
我正在嘗試了解查詢基本HABTM關系的最佳方法。 我想按相關學科找到所有種族。 由於我中間有一個HABTM關系,因此我對執行此操作的最佳方法感到困惑。
class Discipline < ActiveRecord::Base
has_many :event_types
end
class EventType < ActiveRecord::Base
belongs_to :discipline
has_and_belongs_to_many :races
end
class Race < ActiveRecord::Base
has_and_belongs_to_many :event_types
end
謝謝。
您可以對加入event_types的種族進行查詢,並使用where僅包括紀律編號正確的條目。
Race.joins(:event_types).where('event_types.discipline_id = ?', discipline.id)
假設您已將學科加載到變量discipline
……如果您將學科存儲在實例變量@discipline
則相應地更改查詢的結尾。
也許可以這樣定義它:
class Discipline < ActiveRecord::Base
has_many :event_types
has_many :races, through: :event_types
然后只需致電discipline.races
。
我認為,如果沒有,這應該起作用:
discipline.event_types.includes(:races).map { |e| e.races }.flatten
map
返回一個新的Array,其中包含每個結果的塊結果,因此每個事件的競賽。 flatten
使嵌套數組(每個事件類型的競賽數組)中的一個變為平坦(競賽)。 也許您也想在此上調用uniq
。 並且includes
渴望一次加載所有種族,而不是每個事件類型一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.