檢查以下部分是模型相關的部分:如何獲取這些代理人有效IDS Rails中
ALL_STATUS = ['approved', 'pending', 'processing', 'declined', 'rejected']
#agent.rb
has_many :reports
has_many :assessments, through: :reports
#report.rb
has_many :assessments
belongs_to :agent
#assessment.rb
belongs_to :agent
Those are my sample records in DB.
#agent
id name
1 Alex
2 Justin
3 Clark
4 Mike
#reports
id agent_id status
1 1 approved
2 1 pending
3 1 processing
4 1 rejected
#assessment
id report_id agent_id status
1 1 1 approved
2 3 1 processing
3 2 1 pending
4 4 1 rejected
說明:
- 一旦我們創建報告那些越來越轉換爲評估 記錄。
- 此處添加了代理商#Alex(user_id:1)提交的報告以進行評估。
- 我想找出那些所有評估都沒有的用戶標識添加/拒絕其報告已添加到 評估列表的那些用戶標識?
- 所以這裏的輸出將只是[2,3,4]。
我使用下面的代碼來獲得這些代理ID(這些ID可能有報告記錄,但可能沒有任何評估)。
eligible_agents = []
result = Agent.joins(:reports, :assessments)
result.each do |agent|
if(agent.reports.pluck(:status).count !=agent.assessments.pluck(:status).count)
eligible_agents.push agent.id
end
end
這裏的問題是清晰可見的,如果報告/評估的數量增長,然後查詢本內,如果條件是要運行多次。
我們可以在這裏找到更好的解決方案嗎?