Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 more elegant solutions?

like image 698
sscirrus Avatar asked Nov 03 '10 08:11

sscirrus


3 Answers

One line:

<%= @cars.map(&:id).join(",") %>
like image 183
PeterWong Avatar answered Oct 02 '22 00:10

PeterWong


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!

like image 45
php_on_rails Avatar answered Oct 01 '22 23:10

php_on_rails


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.

like image 27
grouchomc Avatar answered Oct 01 '22 23:10

grouchomc