多对多关系的复选框 [英] Checkbox for many-to-many relationship

查看:56
本文介绍了多对多关系的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 的记录

I need to show checkboxes for each roles that a Player can playing. A checkbox checked means a record on "playing_roles" relashionship

在 Rails4 中使用 collection_check_boxes:

Using collection_check_boxes: in Rails4

更新

如果我使用 :playing_role_ids 我得到这个错误:

If I use :playing_role_ids I get this error:

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

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

It seems that it's looking for the record on the relationship, but if a record doesn't exist it means there isn't a relationship and the checkbox must be unchecked.

推荐答案

在 Rails 3.x 中,使用 simple_form:

In Rails 3.x, use simple_form:

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

在 Rails 4 中,使用 collection_check_boxes 编写

In Rails 4, using collection_check_boxes write

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

您必须使用名称 :playing_roles_ids,因为您要分配 ID 而不是 PlayingRoles.

You have to use the name :playing_roles_ids because you are assigning IDs and not PlayingRoles.

这篇关于多对多关系的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆