Using capitalization on a collection_select

If they answered before I couldn’t find him.

I have the following:

= f.collection_select :sex_id, @sexes, :id, :name 

and this is in the controller:

 @sexes = Sex.all 

all floors are stored in lower case, for example:

 id|name 1|steer 2|heifer 3|holstein 

I need them to be displayed with the letters "First letter":

 Steer Heifer Holstein 

I tried:

 = f.collection_select :sex_id, @sexes, :id, :name.capitalize = f.collection_select :sex_id, @sexes, 'id', 'name'.capitalize 

but they don’t work, and I didn’t really expect them, but I had to try them before publishing it.

+7
collections capitalize ruby-on-rails
source share
3 answers

collection_select calls a method for each object to get the text for the parameter value. You can add a new method to the model to get the correct value:

 def name_for_select name.capitalize end 

then in the view:

 = f.collection_select :sex_id, @sexes, :id, :name_for_select 
+6
source share

The reason your initial attempt does not work is because you are trying to use a character or string that represents a field name, and not a real variable.

You can do something like this, and then the data will be capitalized before it is sent to the view.

 @sexes = Sex.all @sexes = @sexes.each{|sex| sex.name.capitalize} 

or

 @sexes = Sex.all.each{|sex| sex.name.capitalize} 
0
source share

An easy way to do this in RoR4 would be to use the humanize method. So your code will look like this:

 = f.collection_select :sex_id, @sexes, :id, :humanize 

No additional methods needed!

0
source share

All Articles