[英]How can I select all records from one table and if their id is present in another then get data from table 2 also?
I want to get an array of all players back and the ones that have been added to TeamSelections I would like to be able to get their data from that table also. 我想找回所有球员的数组,以及已经添加到TeamSelections的球员,我也希望能够从该表中获取他们的数据。 How do I go about this? 我该怎么办?
class CreatePlayers < ActiveRecord::Migration[5.1] def change
create_table :players do |t|
t.belongs_to "club", index: true
t.belongs_to "club_rl", index: true
t.string "nickname"
t.string "first_name"
t.string "middle_names"
t.string "last_name"
t.date "dob"
t.string "pob"
t.string "position"
t.integer "number"
t.string "height"
t.boolean "international", default: false
t.string "national_team"
t.timestamps
end end end
class CreateTeamSelections < ActiveRecord::Migration[5.1]
def change
create_table :team_selections do |t|
t.belongs_to "season", index: true
t.belongs_to "club", index: true
t.belongs_to "player", index: true
t.integer "fixture_week"
t.integer "position", limit: 1
t.timestamps
end
end
end
ActiveRecord
includes should do this for you quite well. ActiveRecord
includes应该可以为您做得很好。 As you want to iterate over all players
and put player position if he/she is in a team_selection
. 如您要遍历所有players
并在其team_selection
位置时放置玩家位置。
(PS - Assumed a player has_many :team_selections if its has_one then please use team_selection instead of team_selections) (PS-假设玩家has_many:team_selections,如果其has_one,则请使用team_selection而不是team_selections)
Player.includes(:team_selections).each do |p|
if p.team_selections.present?
# insert their position in the HTML element
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.