通过has_many访问其他模型属性

时间:2018-04-19 16:57:53

标签: ruby-on-rails

我希望能够在视图中以这种方式调用另一个表中的值。

<%= @team.r1.players.full_name %>
<%= @team.r2.players.full_name %>
...
<%= @team.r2.players.full_name %>

r1r10是包含玩家ID的列。

模型非常简单,看起来像这样。

class Player < ApplicationRecord
  has_and_belongs_to_many :teams
end

class Team < ApplicationRecord
  belongs_to :user
  has_many :players
end

结果的错误是未定义的方法`玩家'为3:整数。我试图尝试使用单数和复数版本来提取它但会发生同样的错误。看起来你可以做一个连接表,但这不是理想的或做一个has_many:通过关联。

模式

  create_table "players", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "full_name"
  end

  create_table "team_players", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "teams", force: :cascade do |t|
    t.bigint "user_id"
    t.string "team_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "r1"
    t.integer "r2"
    t.integer "r3"
    t.integer "r4"
    t.integer "r5"
    t.integer "r6"
    t.integer "r7"
    t.integer "r8"
    t.integer "r9"
    t.integer "r10"
    t.index ["user_id"], name: "index_teams_on_user_id"
  end

我以这种方式在团队中设置更新/添加玩家。

<%= f.collection_select(:r1, Player.all, :id, :full_name , {required: true, include_blank: false}, {class: 'uk-input'}) %>

1 个答案:

答案 0 :(得分:1)

正如ConorB在评论中所说,r1r2等位似乎很奇怪。如果你想限制团队中的玩家数量,我建议你在代码中而不是数据结构中这样做。

作为备注:在您的Team模型中,您说:

class Team < ApplicationRecord
  belongs_to :user
  has_many :players
end

根据docs

  

has_many关联表示与另一个模型的一对多连接。

这不是你的情况。您在TeamPlayer之间拥有多对多的基数。因此,在您的情况下使用has_many而不使用through是错误的。

你应该拥有的是:

class Player < ApplicationRecord
  has_many :team_players
  has_many :teams, through: :team_players
end

class Team < ApplicationRecord
  has_many :team_players
  has_many :players, through: :team_players
end

class TeamPlayer < ApplicationRecord
  belongs_to :team
  belongs_to :player
end

然后做:

<% @team.players.each do |player| %>
  <%= player.full_name %> 
<% end %>

可以决定使用has_and_belongs_to_many,在这种情况下,您需要一个teams_players表,但不需要TeamPlayer模型。 (就个人而言,我从不使用HABTM,但这纯粹是个人偏好。)有关详细信息,请参阅guide