Topic: Comma Separation

Hi,

In my web app I have a one-to-many relationships so a ticket can belong to many departments, and so when displaying the list of departments I would like to separate them with commas, I have a loop doing this but there must be a better way, if anyone can make a helper I can pass a collection to and specify an attribute I want to join with commas that would be great.

Here is my current code:

<%
@itter = 0
for dpt in @ticket.departments do
    if @itter > 0
        %>,<%
    else
        @itter = 1
    end
%> <%= dpt.name %><% end %>

I would ideally like to be able to do something like below, but any better way would be greatly appreciated.

list_collection(@ticket.departments, 'name', ',')

Cheers. R

ThinkRefresh - Free Rails Techniques Screencasts

Re: Comma Separation

<%= @ticket.departments.map{ |d| d.name }.join(",") %>

Basic Ruby.

If you don't have already, get a Book about Ruby (not Rails!) and get to know the language you code in a bit better, no pun intended. wink

Last edited by Duplex (2007-11-22 13:19:47)

Re: Comma Separation

Brilliant, thanks!

ThinkRefresh - Free Rails Techniques Screencasts

Re: Comma Separation

If you're just getting a single attribute out you can also use the shorthand, though I think it might be a little slower.

<%= @ticket.departments.map(&:name).join(',') -%>