Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Change checkbox label in formtastic

I am using formtastic to render a form for a object of a model that has a HABTM relationship with another model.

I am doing this to render a list of checkboxes:

<%= f.input :classes, :as => :check_boxes, :collection => UserClass.all %>

And yes, it renders all the checkboxes and at the right side it shows the object name, something like this. So I have something like this:

[x] #<UserClass:0x000000087e4958>

How can I change that? I want to show the class name and description...

Thank you.

like image 231
Hommer Smith Avatar asked Dec 13 '22 04:12

Hommer Smith


1 Answers

Use the :member_label option:

<%= f.input :classes, :as => :check_boxes,
    :collection => UserClass.all, :member_label => :name %>

(Assuming your UserClass has a name attribute, for example). If your label comes from multiple fields, you can pass a Proc. For example (if your UserClass has first_name and last_name attributes):

<%= f.input :classes, :as => :check_boxes,
    :collection => UserClass.all,
    :member_label => Proc.new { |u| "#{u.first_name} #{u.last_name}" } %>

The above is for Formtastic version 2.x. For the 1.2-stable branch, it works the same (you can pass in a method name or proc) but the option is called :label_method. Example:

<%= f.input :classes, :as => :check_boxes,
    :collection => UserClass.all, :label_method => :name %>
like image 148
Ben Lee Avatar answered Dec 25 '22 03:12

Ben Lee