2013-07-03 53 views
0

控制器AssociationTypeMismatch爲collection_check_boxes

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(文檔)產生

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=""> 

它似乎正確地顯示所有,但是當我點擊提交按鈕,我得到這個錯誤: enter image description here

+0

你可以添加控制器動作的代碼? –

+0

@MichaelSzyndel done;) – sparkle

+0

@ user1028100你可以粘貼完整的回溯? –

回答

4

對不起,我以爲這雖然很複雜,但我不認爲這是事實。

您正在告訴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和文本方法:name

然後,在更新中,它會將這些ID保存到Player上的player_role_ids屬性,從而導致關聯生成。

參見: Rails has_many :through and collection_select with multiple

相關問題