Fernando Aureliano
Fernando Aureliano

Reputation: 914

Rails4: collection_check_boxes from array

There is some way to serialize a collection_check_boxes from one constant? Something like this:

# model
class tutorial < ActiveRecord::Base
  serialize :option
  TYPES = ["Option 1", "Option 2", "Option 3"]
end

# view
<%= form_for(@tutorial) do |b| %>
  <%= f.collection_check_boxes(:option, Tutorial::TYPES, :id, :name) do |b| %>
         <%= b.label class:"label-checkbox" do%>
         <%=b.check_box + b.text%>
      <%end%>
   <% end %>
<% end %>

Or just:

<%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>

When I try both it I get the error:

undefined method `id' for "Option\t1":String

My permit parameters are already set with option: []

Someone did something like that before?

Thanks!

Upvotes: 0

Views: 1734

Answers (1)

Vasili
Vasili

Reputation: 905

The definition is:

collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)`

The first one is a method to send, the second is a collection, the third is a method which is called to set an option value property, and the fourth is a method that is called to get a text and place it as a label for an option.

<%= f.collection_check_boxes :option, Tutorial::TYPES, :id, :name %>

There you are using Tutorial::TYPES (which is an array if strings) as a collection, and call id and name methods on each string.

Your collection should be Tutorial.all, and to get a label, you should implement a method on a Tutorial object for that, for example:

enum type: [
  :type1,
  :type2,
  :type3,
]

And use it like this:

<%= f.collection_check_boxes :option, Tutorial.all, :id, :type %>

Upvotes: 1

Related Questions