2017-02-12 86 views
0

我相信我的措辭不是很好,這解釋了爲什麼我在搜索失敗。我試圖找出如何識別與其他兩個相關的記錄。例子會使它更清晰。如何識別包含Ruby on Rails相關記錄的模型?

模型比賽 has_many與結果。結果有一個團隊號碼(但可以使用字母作爲清晰度)

因此,在此示例中,我試圖找出A隊和D隊都參加過的所有比賽。

我想找回所有符合這個條件的比賽的調查員,然後我可以將兩個隊伍相互比較。

我很抱歉,這不是最好的寫作,我正在努力的條款來定義我想要做的事情。感謝您的幫助,時間和耐心!

回答

0

考慮:

class Contest < ApplicationRecord 
    has_many :results 
    has_many :teams, through: :results 
end 

class Result < ApplicationRecord 
    has_many :teams 
    belongs_to :contest 
end 

class Team < ApplicationRecord 
    belongs_to :result 
    delegate :contest, to: :result 
end 

這將設置你的協會,並讓你從Team訪問Contestdelegate方法說:「如果我撥打team.contest,請改爲team.result.contest」。

希望有幫助!

編輯

如果你想收集的比賽:

Contest.joins(results: :teams).where(teams: { id: team_a.id }) Contest.joins(results: :teams).where(teams: { id: team_b.id })

+0

感謝您!我應該列入包括我已經建立了模型,但現在很高興我沒有!我不知道在模型中的代表,總是用「通過:」選項底部的代碼是非常讚賞的回答這個問題爲好,感謝你,我給它一個去! – MechDog

0

問題是你需要與A隊參加同一個表兩次,一次結果和一次與團隊B的結果。您需要將它們作爲單獨的表格引用。您可以使用阿雷爾和分配唯一的名稱表中的兩個實例。

contests_between = Arel::Table.new(:contests, as: 'contests_between') 
team_a_results = Arel::Table.new(:results, as: team_a_results) 
team_b_results = Arel::Table.new(:results, as: team_b_results) 

relation = contests_between.project(Arel.sql('*')). 
join(team_a_results).on(contests_between[:id].eq(team_a_results[:contest_id])). 
join(team_b_results).on(contests_between[:id].eq(team_b_results[:contest_id])) 

And then you can do... 

relation = relation.where(team_a_results[:team_id].eq(1)).where(team_b_results[:team_id].eq(2)) 

@contests = relation.to_sql 

# above assumes team_a is id 1 and team_b is id 2... if the teams are already loaded you could substitute team_a.id and team_b.id