开发者

Rails: display @cars as a comma-separated list

开发者 https://www.devze.com 2023-01-23 10:57 出处:网络
Based on this query: @cars = Car.where(\"manufacturer_id IN ?\", @mfts.select(\"id\")).limit(30).select(\"id\")

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.

0

精彩评论

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