简体   繁体   中英

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. 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. As you want to iterate over all players and put player position if he/she is in a team_selection .

(PS - Assumed a player has_many :team_selections if its has_one then please use team_selection instead of team_selections)

Player.includes(:team_selections).each do |p|
  if p.team_selections.present?
    # insert their position in the HTML element
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM