4

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.

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

2 Answers2

14

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 %>
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • Thanks for the quick answer. I have tried that, and also the :value_method, but I still see the # . Any thoughts? – Hommer Smith Mar 25 '12 at 23:50
  • @HommerSmith, in 1.2 the option was called `:label_method`. I updated my answer to incldue that. – Ben Lee Mar 26 '12 at 00:08
  • Awesome! Why have they changed the name of that option that much? :P – Hommer Smith Mar 26 '12 at 00:12
  • @HommerSmith, For the transition from version 1 to version 2, the code was heavily gutted and massively re-factored. Just one change among the storm. – Ben Lee Mar 26 '12 at 00:14
-1

TRemove the render from the tag. Use <% instead of <%=

thanks @HommerSmith for clearing things up regarding the use in older versions and where to use the above example.

Galuga
  • 531
  • 2
  • 6
  • @HommerSmith, Galuga is right. In version 1.2 you omit the `=`, the render is build in. But also see my answer for how to do what you want in 1.2. – Ben Lee Mar 26 '12 at 00:11
  • @HommerSmith, hmm... I thought it did the render automatically, but if not, I guess just keep using the `<%=` ;) – Ben Lee Mar 26 '12 at 00:15
  • 1
    @HommerSmith, actually nevermind. You were right from the start, you *do* need `<%=`, you only omit it from `form.inputs`, not from `form.input`. But note that this *is* different from the newer version, where you use `<%=` even for `form.inputs`. – Ben Lee Mar 26 '12 at 00:17
  • @Ben Lee Ok. Thanks for your time and accurate answer. – Hommer Smith Mar 26 '12 at 00:19