Rails: display @cars as a comma-separated list
Based on this query:
@cars = Car.where("manufacturer_id IN ?", @mfts.select("id")).limit(30).select("id")
How can I display the cars' IDs in the view like this (or do I need to rewrite my query)?
3,2,5,12,15,24,34,63,64,65,66,85
Thanks a lot - I've looked for this but couldn't find the right question/answer.
One solution is to do:
#view
<% @cars.each do |c| %><%= c.id %>,<% end %>
I don't know if there's a better way to go about it - this obviously leaves a stray comma at the end of the list (which isn't a dealbreaker). Any m开发者_JS百科ore elegant solutions?
One line:
<%= @cars.map(&:id).join(",") %>
If writing &:id
seems confusing, there's another way that's a little more readable.. If y'all want to access a method or attribute, it might look better to inline a block.
<%= @cars.map { |car| car.id }.join(", ") %>
P.S... another name for map
is collect
.. that's what it's called in Smalltalk.
Lookin' good!
With Rails 3.0+ you can now write:
<%= @cars.map { |car| car.id }.to_sentence %>
Rails will appropriately add the comments and the word 'and' between the last two elements.
精彩评论