0

控制器

class PlayerProfilesController < InheritedResources::Base

    def show
        @player_profile = PlayerProfile.find(params[:id])
    end
end

模型

class PlayerProfile < ActiveRecord::Base

  has_many :playing_roles, :dependent => :destroy
  has_many :player_roles, through: :playing_roles

end

class PlayerRole < ActiveRecord::Base

   has_many :playing_roles, :dependent => :destroy 
   has_many :player_profiles, through: :playing_roles

end

class PlayingRole < ActiveRecord::Base
  belongs_to :player_profile
  belongs_to :player_role

end

显示.html.erb

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

collection_check_boxes (文档)

为两个复选框生成的 HTML

<input id="player_profile_playing_roles_1" name="player_profile[playing_roles][]" type="checkbox" value="1" class="hidden-field">
<span class="custom checkbox checked"></span>
<label for="player_profile_playing_roles_1">Striker</label>

<input id="player_profile_playing_roles_2" name="player_profile[playing_roles][]" type="checkbox" value="2" class="hidden-field">
<span class="custom checkbox"></span>
<label for="player_profile_playing_roles_2">Midfielder</label>
<input name="player_profile[playing_roles][]" type="hidden" value="">

似乎它显示正确但是当我单击提交按钮时出现此错误: 在此处输入图像描述

4

1 回答 1

4

抱歉,我认为这很复杂,但我不这么认为。

您是在告诉collection_check_boxes期望:playing_roles,然后通过PlayerRole.all. 那就是不匹配。AssociationTypeMismatch 是当你告诉一个对象关联一个 Duck 但然后将它传递给一个 Helicopter 时。

你需要这样做:

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

你告诉它期望,你传递给它一个带有值方法和文本方法:player_role_ids的集合。PlayerRole.all:id:name

然后,在更新中,它将这些 id 保存到player_role_idsPlayer 的属性中,从而建立关联。

另请参阅: Rails has_many :through 和 collection_select with multiple

于 2013-07-09T15:36:50.617 回答