0

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!

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

4 Comments

But using 'Tutorial.all' I do a query from model. This is exactly what I do not want to do. Whats I need is call it from array, like we do when we use the 'select' helper: <%= f.select(:lang, options_for_select(User::LANGS, @user.lang), {}, {} ) %>
@FernandoAureliano okay, then two last elements should not be :id and :name because these are methods that you call on each element of collection, so you're trying to call :id and :name on "Option 1":String. You can change TYPES to hash where keys or values are indices, and use it like that: <%= f.collection_check_boxes :option, Tutorial::TYPES, :key, :value %>.
Got the same error undefined method key' for [1, using an array like: [[1, "option 1"], [2, "option 2"], [3, "option 3"]]
@FernandoAureliano of course, if you're using an array, there's no key or value methods. You should use :first and :last instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.