3
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

Player がプレイできるロールごとにチェックボックスを表示する必要があります。チェックボックスがチェックされていることは、「playing_roles」関係の記録を意味します

collection_check_boxes:を Rails4 で使用する

アップデート

:playing_role_idsを使用すると、次のエラーが発生します。

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

ここに画像の説明を入力

関係のレコードを探しているようですが、レコードが存在しない場合は関係がないことを意味し、チェックボックスをオフにする必要があります。

4

2 に答える 2

8

Rails 3.x では、simple_formを使用します。

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

Rails 4 では、collection_check_boxeswriteを使用して

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

:playing_role_idsPlayingRoles ではなく ID を割り当てるため、名前を使用する必要があります。

于 2013-07-02T21:49:44.820 に答える
0

Rails 4 を使用している場合は、以下を使用できるはずですcollection_check_boxes: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes

于 2013-07-02T21:41:17.823 に答える