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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With