무작위로 선택된 Matchup 오브젝트를 가져 오는 ActiveRecord 쿼리가 있는데,이 플레이어는 현재 대전 상대가 "Bye Week"인 팀에 속하지 않습니다.리팩토링 ActiveRecord 쿼리
모델의 정의 :
매치업은 플레이어 오브젝트의 ID 두 개의 필드, player_1 및 player_2을 가지고 있습니다.
각 플레이어 belongs_to 팀. 여러 개의 필드가 있습니다 (예 : opponent_week_1, opponent_week_2 ... opponent_week_17.
current_week는 오늘 날짜를 기준으로 1에서 17 사이의 정수를 반환합니다 (현재 NFL 시즌의 주를 결정 함).
는 지금은 이런 식으로 일을하고있다,하지만 난 조건 충족, 무작위로, 루프를 제거하고 개체를 선택하려면 그냥 쿼리를 사용하고 싶습니다 :
def getRandomMatchup
current_week = view_context.current_week
matchup = Matchup.order("RANDOM()").first
opponent1 = Team.find(Player.find(m.player_1).team.send("opp_week_#{current_week}")).name
opponent2 = Team.find(Player.find(m.player_2).team.send("opp_week_#{current_week}")).name
while opponent1 == "Bye Week" || opponent2 == "Bye Week"
matchup = Matchup.order("RANDOM()").first
opponent1 = Team.find(Player.find(matchup.player_1).team.send("opp_week_#{current_week}")).name
opponent2 = Team.find(Player.find(matchup.player_2).team.send("opp_week_#{current_week}")).name
end
return matchup
end
내 생각되었다 같은 것을 할,하지만 난 그것을 정확하게 실행하는 방법을 잘 모르겠어요하기 :
m = Matchup.where.not(Team.find(Player.find(m.player_1).team.send("opp_week_#{current_week}")).name: "Bye Week",
Team.find(Player.find(m.player_2).team.send("opp_week_#{current_week}")).name: "Bye Week").order("RANDOM()").first
을 내가 루비 2 레일을 사용하고 4
글쎄, 그건 조금 혼란. 그렇다면'player_1'과'player_2' 외래 키가 있습니까, 아니면 실제 플레이어 객체를 반환하는 메소드입니까? 또한'send'를 통해 호출되는 메소드의 정의를 게시 할 수 있습니까? – depa
나는 데파에게 두 번째. 귀하의 테이블 구조를 붙여주십시오. 그리고 유행에있는 몇몇보기를 제공하십시오 : 이들은 나가 가지고있는 기록이다 ..... ..... 나는 이것들을 가져오고 싶다 : ...... –
그래, 적어도 팀, 선수, 그리고 Matchup가 어떻게 연관지를 게시해라. 그리고 설명적인 변수 이름을 사용하십시오! '''''''',''o2'',''m''은 독자에게 아무 것도 말하지 않는다. – jcm