简体   繁体   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?

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.

相关问题 从一个表中获取不在第二个表的任何列中的所有记录 - Get all records from one table that are not in either column of a second table 如何从一个表获取不在另一表的字段中的记录(3) - How to get records from one table which are not in another table's fields (3) 从另一个表获取没有记录的记录 - get records without records from another table 如何从另一个表的ID中获取名称 - How to get the name from an ID in another table 如何将表格列数据从一种模型导入另一种模型的视图? - How do I get the table column data from one model into the view of another? 如何在Rails 5中从具有匹配ID的联接表中获取记录数 - How to get count of records from join table with matching ID in Rails 5 在Rails迁移中,如何将数据从一个表移动到另一个表? - How can I move data from one table to another in rails migration? 从表中获取记录,该记录的 ID 在特定用户的另一个表中不存在 - Get the records from a table which id does not exist in another table for a specific User Rails 4-如果在另一个表中不是特定记录,如何从一个表中选择数据? - Rails 4 - How to select data from a table if in another table is not a specific record? 如何使用很少的选项从连接表中选择数据记录? - How to select data records from join table with few options?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM