多对多关系的复选框

2023-12-22

class PlayerProfile < ActiveRecord::Base

  has_many :playing_roles
  has_many :player_roles, through: :playing_roles

  accepts_nested_attributes_for :playing_roles, :allow_destroy => true

end

class PlayingRole < ActiveRecord::Base
      belongs_to :player_roles
      belongs_to :player_profile
 end

class PlayerRole < ActiveRecord::Base
  has_many :playing_roles
  has_many :player_profiles, through: :playing_roles
end 

架构.rb

    create_table "player_profiles", force: true do |t|
    t.integer  "user_id"
    t.string   "firstname"
    t.string   "lastname"
    t.date     "birthdate"
    t.string   "favorite_team"
    t.string   "mobile"
    t.string   "address"
    t.string   "lang"
    t.string   "team"
    t.integer  "weight"
    t.integer  "height"
    t.text     "biography"
    t.string   "idols"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "nationality"
  end
  add_index "player_profiles", ["user_id"], name: "index_player_profiles_on_user_id", using: :btree
  create_table "player_roles", force: true do |t|
    t.string "name"
  end
  create_table "playing_roles", force: true do |t|
    t.integer  "player_profile_id"
    t.integer  "player_role_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我需要为玩家可以扮演的每个角色显示复选框。勾选复选框表示记录“扮演角色”关系

Using 集合复选框:在Rails4中

UPDATE

如果我使用:playing_role_ids我收到此错误:

<%=collection_check_boxes(:player_profile, :playing_role_ids, PlayerRole.all, :id, :name)%>     

它似乎正在寻找关系上的记录,但如果记录不存在,则意味着不存在关系,并且必须取消选中该复选框。


在 Rails 3.x 中,使用简单的形式 https://github.com/plataformatec/simple_form:

<%= simple_form_for @player_profile do |f| %>
  <%= f.association :player_roles, as: :check_boxes %>
  ...
<% end %>

在 Rails 4 中,使用collection_check_boxes write

<%=collection_check_boxes(:player_profile, :playing_role_ids, PlayerRole.all, :id, :name)%> 

你必须使用这个名字:playing_role_ids因为您分配的是 ID,而不是 PlayingRoles。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多对多关系的复选框 的相关文章

随机推荐