Rails:将@cars显示为以逗号分隔的列表

时间:2022-01-21 00:17:00

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)?

如何在这样的视图中显示汽车的ID(或者我是否需要重写我的查询)?

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?

我不知道是否有更好的方法可以解决这个问题 - 这显然会在列表末尾留下一个流浪逗号(这不是一个破坏者)。更优雅的解决方案?

3 个解决方案

#1


29  

One line:

<%= @cars.map(&:id).join(",") %>

#2


8  

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.

如果编写&:id似乎令人困惑,那么另一种方式更具可读性。如果你们都想要访问一个方法或属性,那么内联一个块可能看起来更好。

<%= @cars.map { |car| car.id }.join(", ") %>

P.S... another name for map is collect.. that's what it's called in Smalltalk.

P.S ......地图的另一个名称是收集..这就是它在Smalltalk中的名称。

Lookin' good!

#3


5  

With Rails 3.0+ you can now write:

使用Rails 3.0+,您现在可以编写:

<%= @cars.map { |car| car.id }.to_sentence %>

Rails will appropriately add the comments and the word 'and' between the last two elements.

Rails会在最后两个元素之间适当地添加注释和单词“and”。

#1


29  

One line:

<%= @cars.map(&:id).join(",") %>

#2


8  

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.

如果编写&:id似乎令人困惑,那么另一种方式更具可读性。如果你们都想要访问一个方法或属性,那么内联一个块可能看起来更好。

<%= @cars.map { |car| car.id }.join(", ") %>

P.S... another name for map is collect.. that's what it's called in Smalltalk.

P.S ......地图的另一个名称是收集..这就是它在Smalltalk中的名称。

Lookin' good!

#3


5  

With Rails 3.0+ you can now write:

使用Rails 3.0+,您现在可以编写:

<%= @cars.map { |car| car.id }.to_sentence %>

Rails will appropriately add the comments and the word 'and' between the last two elements.

Rails会在最后两个元素之间适当地添加注释和单词“and”。