Using check_box with a list of objects

I am having trouble figuring out how to use a check box with a list of

I have two models, players and player_stats





I want to present a list of players, and use a check box to determine
if a player_stat should be created for that player. In my view I’m
trying to do something like this.

<% for @player in @players %>

<%= check_box( "player[]", ... ) %> <%= %> <% end %>

I don’t know what to use as the method in the check_box() call. The
check box doesn’t specify an attribute in either model, I want it to
signify that a player_stat should be created.

Is there a better way to approach this? I want to show the user a list
of all players. The user will then select the players that played in a
game, and a row in player_stats will be created.


That looks like an ok approach. You set the checkbox name to something
like stats[1], stats[2]. Then in the controller just use
params[:stats][‘1’]. That way it’s independent of your player record.
Another way is to include the stats field in the player record and
remove it before passing params to the model.


Well, I changed the check_box() method in the view to the following:

<%= check_box("player[]", 'stats[1]') %>

I now get this error.
undefined method `stats[1]’ for #Player:0x41a5c0e4

Here is what the api doc says check_box is expecting.
“Returns a checkbox tag tailored for accessing a specified attribute
(identified by method) on an object assigned to the template
(identified by object). It’s intended that method returns an integer
and if that integer is above zero, then the checkbox is checked.”

So, “stats” is not an attribute of Player, and that is why I’m getting
the error.

Each row in player_stats tells me that a player played in a game. Will
adding a “played” column to player_stats solve the problem?


OK, here’s the solution I’ve come up with.

  1. I added a column to player_stats named ‘played’.

  2. When getting my list of players, I left join player_stats so that I
    get a list of players even if no row in player_stats exists.

  3. I use ‘played’ as the method in my call to check_box().

The ‘played’ column seems a bit redundant, if the row exists in
player_stats, played will always be 1. I couldn’t think of another
solution, though.

Here is what the view code looks like and the corresponding html.


<%= check_box("visiting_player[]", 'played') %> <%= @visiting_player.person.last_name %>, <%= @visiting_player.person.first_name %>


Jones, Matt

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs