What is the most elegant way in Rails to create a comma-separated list inside a partial?
I've just recently discovered that you can use partials to iterate through a collection sent from another view template. So in the view template I have:
<% render @dvd.director %>
Then in /view/directors/_director.html.erb:
<%= director.director %>
This actually does something like:
@dvd.director.each { |d| puts d.director }
Now, I know I could use a .join like so:
<% @dvd.director.map { |t| t.director }.join(", ") %>
But since the partial already iterates through each entry in the array, how can I separate the lists properly and not have the last one (or a single one) with an ugly comma at the end?
A lot of entries will have only one director, I just want to separate those that have more than one properly. I know I can do all this manually (using a normal, non-iterating partial and creating the .each loop myself), but am trying to do it, and learn, the Rails way.
Thanks.
Edit
To try to explain a little better, @dvd.director returns an ActiveRelation object like so:
[#<Director id: 13, director: "Andrew Stanton">, #<Director id: 14, director: "Lee Unkrich">]
So I can't just do @dvd.director.join(', ')
Is there another way to get that data other than
@dvd.director.each { |dir| dir.director }
Because there I have the same problem, I have to count them or make sure it's not the last item before I put a comma between them, or extract just the director names and put them into a string or something like that. If I could do a join it would be great.
Ruby's join method won't add the separator character if there is only a single element in the array.
You should be able to do the following for a list of any size:
@dvd.director.map(&:director).join(", ")
来源:https://stackoverflow.com/questions/9360984/rails-separate-array-items-with-comma-inside-partial