简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM