Ben Smith Ben Smith - 1 year ago 84
Ruby Question

Ruby on Rails: Add a check box for each value in database

I am trying to display checkboxes on a form that show all of the contacts for a user, so that the user can then select the contacts required. I have done this on the form so far, which displays the checkboxes but with no value:

<% @contacts.each do |contact| %>
<% if == User.find(session[:user_id]).id %>
<%= f.check_box :to %>
<% end %>
<% end %>

But when I try to change the line
<%= f.check_box :to %>
<%= f.check_box :to, %>
to show the email address of the contact I get the error:

undefined method `merge' for "":String

Is there a way around this? I have looked at multiple posts before and tried various options but none seem to help, including:

Ruby on rails f.label for a check box
How to add a checkbox for each row in Rails 3.2 index page?

Answer Source

You have too much logic in the view. I can't see your code, but I can give you some recommendations:

In the controller:

@contacts_of_current_user = @contacts.where(user_id: session[:user_id])


<% @contacts_of_current_user.each do |contact| %>
      <%= f.label :to, %>
          <%= f.check_box :to, {}, %>
      <% end %>
<% end %>


From the comments I understood that you need to get a string of chosen emails.

There are two ways you can do it.

1) Somehow build this string on the client side (JavaScript)

2) Or pass an array of emails and then concatenate them into single string on the server

I can show you how you can pass an array:

<%= f.collection_check_boxes(:to, @contacts, :email, :email ) %>

Or you can do it manually, something like this:

  <% @contacts_of_current_user.each do |contact| %>
      <%= f.label :to, %>
          <%= check_box_tag 'to[]', %>
      <% end %>
<% end %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download