Rails how to call helpers such as .humanize on an attribute of collection_select
ruby, ruby-on-rails, ruby-on-rails-3
Solution
With Rails 4
Just like this:
`<%= collection_select(:template, :template_id, @templates, :id, Proc.new {|v| v.name.humanize}) %>`
In the `Proc` block, `v` will be your models, iterated through a `each` loop.
`collection_select` works with anything that inherit from `Enumerable` and have no limit in the content of the Proc.
With Rails 3
You must do it your self, by preparing your data before passing it to `collection_select`
# This will generate an Array of Arrays
values = @templates.map{|t| [t.id, t.name.humanize]}
# [ [record1.id, record1.name.humanize], [record2.id, record2.name.humanize], ... ]
# This will use the Array previously generated, and loop in it:
# - send :first to get the value (it is the first item of each Array inside the Array)
# - send :last to get the text (it is the last item of each Array inside the Array)
# ( we could have use :second also )
<%= collection_select(:template, :template_id, values, :first, :last) %>
Problem
I have this collection_select `<%= collection_select(:template, :template_id, @templates, :id, :name) %>` and I want to basically call `:name.humanize`, but obviously that doesn't work. How can i call a method such as `.humanize` on an attribute of collection_select (a hash attribute?) EDIT Here's a snippet from my controller: ``` @templates = Template.select(:name).group(:name) p "templates = #{@templates}" ``` Here's what appears in the console: ``` "templates = #<ActiveRecord::Relation:0x007f84451b7af8>" ```