Rails - Join each
Sorry, I don't really know how to title this question.
Here's my code in view:
<% country.cities.each_with_index do |city, i| %>
<% city.shops.each do |shop| %>
<%=h shop.name.join(", ") %>
<% end %>
<% end %>
So in this city, let's say there are three shops: Walmart, Ace Hardware, Harman Kardon.
The result of the above code would yield:
Walmart Ace Hardware Harman Kardon开发者_如何学编程
How do I join each of them with ", "?
I tried <%= shop.name.join(", ") %>
but not permitted. Error.
Thanks. I love Stack Overflow community. You guys have been more, much more than awesome!
EDIT
I just noticed something. Walmart is in City A; Ace HArdware and Harman Kardon are in City B. That is why it joined city by city.
The code:
<%= shop.name.join(", ") %>
Won't work, because you are already inside the block, and join is a method specific to enumerables, where at this point you just have whatever object.
What you want here is actually:
<%= city.spots.map { |shop| shop.name }.join(", ") %>
The reason this works is because:
city.spots.map { |shop| shop.name }
Will give you an array of the names of all of the shops, which you can then join using the string of your choice.
You may also want to make sure you html escape the names (just in case):
<%= h( city.spots.map { |shop| shop.name }.join(", ") ) %>
EDIT:
As injekt pointed out, and for the purposes of completeness, you can also abuse Symbol#to_proc and use:
<%= city.spots.map(&:name).join(", ") %>
EDIT PART2:
Now that we have the new surrounding block, we need to re-write the expression:
<%= h( country.cities.map { |city| city.shops }.flatten.map { |shop| shop.name }.join(", ") ) %>
Instead of looping over the names you need to join the elements together
<% city.spots.join(', ') %>
should work assuming city.spots is an Array, otherwise you need .map as TreyE used.
Try this !
<% c = [] %>
<% city.spots.each do |shop| %>
<% c << shop.name %>
<%= shop.name %>
<% end %>
精彩评论