控制器
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
endshow.html.erb
<%=collection_check_boxes(:player_profile, :playing_roles, PlayerRole.all, :id, :name)%>盒子 (博士)
为两个复选框生成的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="">它似乎显示的都是正确的,但是当我单击submit按钮时,我得到了以下错误:

发布于 2013-07-09 15:36:50
抱歉,我以为这很复杂,但我不这么认为。
您正在告诉collection_check_boxes期待:playing_roles,但随后通过PlayerRole.all将其传递为PlayerRoles的集合。这就是错配。AssociationTypeMismatch是指当你让一个物体联想一只鸭子,然后把它递给一架直升机。
你需要这样做:
<%= collection_check_boxes(:player_profile, :player_role_ids, PlayerRole.all, :id, :name) %>让它期待:player_role_ids,就可以传递给它一个PlayerRole.all的集合,其中包含值方法:id和text方法:name。
然后,在更新中,它会将这些in保存到Player上的player_role_ids属性中,从而生成关联。
另见:带多个选择
https://stackoverflow.com/questions/17458098
复制相似问题