Getting a list of names from a list of objects
I have an array "Groups". Each of the group-objects has an attribute name. I want to get a list of all those names, and maybe also the corresponding IDs, to put in a drop-down select in rails.
Is there a very ruby way to do this?
In PHP, I'd do something like:
group开发者_C百科_names = Array.new
Groups.each do |group|
group_names << group.name
end
But this doesn't feel very rubyish at all.
Use map
group_names = groups.map{|group| group.name}
or the short form
group_names = groups.map(&:name)
I think what you're looking for is essentially this:
select(object, method, choices, options = {}, html_options = {})
For example:
<%= f.select("type_id", Object.all.collect {|o| [ o.name, o.id ] }) %>
Checkout more options here.
精彩评论