spa*_*kle 3 ruby-on-rails ruby-on-rails-4
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
Run Code Online (Sandbox Code Playgroud)
Schema.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
Run Code Online (Sandbox Code Playgroud)
我需要显示播放器可以播放的每个角色的复选框.选中的复选框表示关于"playing_roles"重新关系的记录
在Rails4中使用collection_check_boxes:
UPDATE
如果我使用:playing_role_ids我收到此错误:
<%=collection_check_boxes(:player_profile, :playing_role_ids, PlayerRole.all, :id, :name)%>
Run Code Online (Sandbox Code Playgroud)

它似乎正在寻找关系中的记录,但如果记录不存在则意味着没有关系,并且必须取消选中该复选框.
在Rails 3.x中,使用simple_form:
<%= simple_form_for @player_profile do |f| %>
<%= f.association :player_roles, as: :check_boxes %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
在Rails 4中,使用collection_check_boxeswrite
<%=collection_check_boxes(:player_profile, :playing_role_ids, PlayerRole.all, :id, :name)%>
Run Code Online (Sandbox Code Playgroud)
您必须使用该名称,:playing_roles_ids因为您要分配ID而不是PlayRoles.
| 归档时间: |
|
| 查看次数: |
3847 次 |
| 最近记录: |