0

I have two models - Client & Topic, with a HABTM relationship between them.

I am trying to generate a series of checkboxes of the topics, on the Client form partial.

This is what I am doing:

<% Topic.all.each do |topic| %>
  <% checked = @client.topics.include?(topic) %>
    <%= f.label(:name, topic.name) %> <%= f.check_box @topics, topic.id %>
<% end %>

This is the error I get:

undefined method `merge' for 1:Fixnum

I know one solution is to use check_box_tag, but that forces me to do the record updating of the associations manually.

So I would rather use the form_helper for the checkbox tag. The docs are a bit confusing to me.

How can I get this to work with f.check_box.

Thanks.

marcamillion
  • 32,933
  • 55
  • 189
  • 380

2 Answers2

0

The code confuses me. What @topics contains? If it's a collection of of Topic then why you are directly accessing Topic model in the view? It would be:

@topics.each.do

rather than you

Topic.all.each

Moreover, you are using @topics as collection inside a loop. How check_box will generate checkbox from a collection?

Please look at the following things:

  1. accepts_nested_attributes_for. you will need this to set in Client model in addition to Client has_many Topic association
  2. fields_for Otherwise, rails will not have any idea that you want to update topic model from this same form.
  3. Check this screencasts to get an idea how you can make it work
HungryCoder
  • 7,506
  • 1
  • 38
  • 51
  • Even if I change the checkbox helper to be: `f.checkbox topic, topic.id` - where the local variable is `topic`, it still gives me that Fixnum error. What am I missing? – marcamillion Oct 08 '12 at 06:35
  • Also the issue is not whether or not the attribute is accessible. It is. I can access the attributes if I do it from the command-line, for instance. I just don't know how to do it using `f.check_box`. – marcamillion Oct 08 '12 at 06:37
  • if you read the links i've given, you will get better idea. specially if you check the screencast. – HungryCoder Oct 08 '12 at 06:38
0

For whatever reason, the form helper doesn't work with check_box.

So, this is the code that works:

<%= check_box_tag "client[topic_ids][]", topic.id, checked %>

According to other answers for similar questions, the helper f.check_box is model bound and the value supplied to the checkbox is implicit from the model on the form. The issue is, I can't figure out how to get the implicit value of the form_helper to produce the correct tag - i.e. client[topic_ids][], so I have had to resort to check_box_tag.

Community
  • 1
  • 1
marcamillion
  • 32,933
  • 55
  • 189
  • 380