Search code examples
ruby-on-railscheckboxhas-and-belongs-to-manyformtastic

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.


Solution

  • 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 %>