gpt4 book ai didi

ruby-on-rails - 多对多关系的复选框

转载 作者:行者123 更新时间:2023-12-03 15:25:41 26 4
gpt4 key购买 nike

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

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

我需要为玩家可以扮演的每个角色显示复选框。选中的复选框表示“playing_roles”relashionship 上的记录

在 Rails4 中使用 collection_check_boxes:

更新

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

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

enter image description here

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

最佳答案

在 Rails 3.x 中,使用 simple_form :

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

在 Rails 4 中,使用 collection_check_boxes 编写

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

您必须使用名称 :playing_role_ids 因为您分配的是 ID 而不是 PlayingRoles。

关于ruby-on-rails - 多对多关系的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17435937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com