Reputation: 7398
Controller
class PlayerProfilesController < InheritedResources::Base
def show
@player_profile = PlayerProfile.find(params[:id])
end
end
Model
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 generated for two checkboxes
<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="">
It Seems that it show all correctly but when I click on submit button I get this error:
Upvotes: 0
Views: 612
Reputation: 1633
Sorry, I thought this was complicated but I don't think it is.
You are telling the collection_check_boxes
to expect :playing_roles
but then passing it a collection of PlayerRoles via PlayerRole.all
. That is the mismatch. AssociationTypeMismatch is when you tell an object to associate a Duck but then pass it a Helicopter.
You need to do this:
<%= collection_check_boxes(:player_profile, :player_role_ids, PlayerRole.all, :id, :name) %>
You tell it to expect :player_role_ids
, you pass it a collection of PlayerRole.all
with value method :id
and text method :name
.
Then, in the update, it'll save those ids to the player_role_ids
attribute on Player, causing the associations to build.
See also: Rails has_many :through and collection_select with multiple
Upvotes: 4