控制器
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
show.html.erb
<%=collection_check_boxes(:player_profile, :playing_roles, PlayerRole.all, :id, :name)%>
collection_check_boxes(docs)
为两个复选框生成的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="">
它似乎显示所有正确但但当我点击提交按钮时,我收到此错误:
答案 0 :(得分:4)
对不起,我觉得这很复杂,但我认为不是。
您告诉collection_check_boxes
期待:playing_roles
,然后通过PlayerRole.all
将其传递给PlayerRoles。那就是不匹配。 AssociationTypeMismatch是指告对象关联Duck但随后将其传递给Helicopter。
你需要这样做:
<%= collection_check_boxes(:player_profile, :player_role_ids, PlayerRole.all, :id, :name) %>
你告诉它期待:player_role_ids
,你传递了一个PlayerRole.all
的集合,其值为方法:id
和文本方法:name
。
然后,在更新中,它会将这些ID保存到Player上的player_role_ids
属性,从而导致构建关联。
另见: Rails has_many :through and collection_select with multiple