开发者

Getting a list of names from a list of objects

开发者 https://www.devze.com 2023-03-02 19:52 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消