8

If this has been answered before I cannot find it.

I have the following:

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

and this in the controller:

@sexes = Sex.all

the sexes are all stored in lowercase, like this:

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

I need them to output with Capital First letters:

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 do not work, and I didn't really expect them to, but had to try them before posting this.

Toby Joiner
  • 4,306
  • 7
  • 32
  • 47
  • 1
    The Wisconsinite in me asks why you're mixing two sexes with a breed. The data's no good! ;-) – Tass Jul 01 '16 at 16:19
  • 1
    My company is weird like that, but it is cool to work in an industry where you can have "animal sex" in a database and nobody thinks you've lost it. – Toby Joiner Jul 02 '16 at 15:20

3 Answers3

8

collection_select calls a method on each object to get the text for the option value. You can add a new method in the model to get the right value:

def name_for_select
  name.capitalize
end

then in the view:

= f.collection_select :sex_id, @sexes, :id, :name_for_select
zetetic
  • 47,184
  • 10
  • 111
  • 119
0

The simpler way to do this in RoR4 would be to use the humanize method. So, your view code would look like this:

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

No need for any extra methods!

0

The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.

You could do something like this and then the data would be capitalized before it's sent to the view.

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

or

@sexes = Sex.all.each{|sex| sex.name.capitalize}
rwilliams
  • 21,188
  • 6
  • 49
  • 55