Ruby on Rails: change checkbox label in formtastic

I use formtastic to render the form for a model object that has a HABTM relationship with another model.

I am doing this to display a list of checkboxes:

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

And yes, it displays all the checkboxes, and on the right it displays the name of the object, something like this. So I have something like this:

 [x] #<UserClass:0x000000087e4958> 

How can i change this? I want to show the name and description of the class ...

Thanks.

+4
source share
2 answers

Use parameter :member_label :

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

(Suppose your UserClass has a name attribute, for example). If your shortcut consists of several fields, you can pass Proc. For example (if your UserClass has attributes first_name and last_name ):

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

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

 <%= f.input :classes, :as => :check_boxes, :collection => UserClass.all, :label_method => :name %> 
+13
source

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

thanks @HommerSmith for troubleshooting issues regarding use in older versions and where to use the above example.

-1
source

Source: https://habr.com/ru/post/1403366/


All Articles