繁体   English   中英

如何从一个表中选择所有记录,并且如果它们的ID在另一个表中,那么又如何从表2中获取数据?

[英]How can I select all records from one table and if their id is present in another then get data from table 2 also?

我想找回所有球员的数组,以及已经添加到TeamSelections的球员,我也希望能够从该表中获取他们的数据。 我该怎么办?

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应该可以为您做得很好。 如您要遍历所有players并在其team_selection位置时放置玩家位置。

(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.

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