代码之家  ›  专栏  ›  技术社区  ›  lastone

如何从一个表中选择所有记录?如果它们的id存在于另一个表中,则还可以从表2中获取数据?

  •  0
  • lastone  · 技术社区  · 7 年前

    所有球员

    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
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Alok Swain    7 年前

    ActiveRecord includes 你应该做得很好。因为你想遍历所有 players 如果他/她处于 team_selection

    (P.S-假设一个玩家有很多:团队选择如果它有一个,请使用团队选择而不是团队选择)

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