显示页面has_many has_one关联上未初始化的恒定红宝石

问题描述 投票:0回答:1

我具有以下协会,其中一个团队有很多球员,而一个球员只有一个球队。

球员正在工作,我可以在球队页面上列出他们,但是,我不能在球员显示页面上列出球队。这是型号和代码

class Player < ApplicationRecord
  has_rich_text :bio
  has_one_attached :photo
  has_one :team_players
  has_one :team, through: :team_players
end

控制器许可证

params.require(:player).permit(:ign, :name, :bio, :photo, :country, :team_id, :estimated_earnings, :role, :twitch_link, :twitter_link, :instagram_link, :games_played, :games_won, :games_lost, :win_percentage, :character)

显示页面

<p>
  <strong>Team:</strong>
  <%= @player.team.name %>
</p>

错误

enter image description here

这是数据库架构

create_table "players", force: :cascade do |t|
    t.string "ign"
    t.string "name"
    t.string "role"
    t.string "twitch_link"
    t.string "twitter_link"
    t.string "instagram_link"
    t.integer "games_played"
    t.integer "games_won"
    t.integer "games_lost"
    t.integer "win_percentage"
    t.string "character"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "country"
    t.integer "estimated_earnings"
  end

  create_table "team_players", force: :cascade do |t|
    t.bigint "player_id", null: false
    t.bigint "team_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["player_id"], name: "index_team_players_on_player_id"
    t.index ["team_id"], name: "index_team_players_on_team_id"
  end

  create_table "teams", force: :cascade do |t|
    t.string "name"
    t.integer "approximate_earnings"
    t.date "established"
    t.date "disbanded"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "country"
  end

Rails控制台结果

irb(main):005:0> Player.all
  Player Load (0.5ms)  SELECT "players".* FROM "players" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Player id: 1, ign: "NadeShot", name: "Matthew Haag", role: "CEO", twitch_link: "hhh", twitter_link: "hhh", instagram_link: "hhh", games_played: 200, games_won: 100, games_lost: 100, win_percentage: 50, character: "NadeShot", created_at: "2020-06-02 14:59:31", updated_at: "2020-06-02 21:13:05", country: "US", estimated_earnings: 100000>]>
irb(main):006:0> TeamPlayer.all
  TeamPlayer Load (0.4ms)  SELECT "team_players".* FROM "team_players" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<TeamPlayer id: 1, player_id: 1, team_id: 1, created_at: "2020-06-04 17:49:46", updated_at: "2020-06-04 17:49:46">]>
ruby-on-rails ruby associations
1个回答
1
投票

更改为单数:

class Player < ApplicationRecord
  has_rich_text :bio
  has_one_attached :photo
  has_one :team_player # instead of team_players
  has_one :team, through: :team_player # instead of team_players
end
© www.soinside.com 2019 - 2024. All rights reserved.