Emit a Comma Separated List of Links From an Array in Your Rails View

Yeah, this post has the WORST title ever, but i tried to litter it with keywords so people struggling can find it easily.

When messing with my Rails views I find that pretty commonly I’m dealing with lists of things i need to use link_to on AND split them with a comma.  Here’s a super simple trick that will help you keep your view cleaner (this is for Haml).  For the sake of this tiny code snippet pretend you are trying to create a list of your recent posts separated by commas:

= raw @recent_posts.collect { |post| link_to post.title, post }.join(",")

By using collect you iterate over your array of recent posts and build each one into a link using the ‘link_to’ helper — THEN just join with a comma and BAM you have a nice html string of links.  Prefix the whole thing with ‘raw’ because if you don’t Rails will emit escaped HTML in your face.




  • David Douglas

    Actually the title led me to it. Thanks

  • David Douglas

    Actually the title led me to it. Thanks

  • Exactly what I was looking for. Rockin’

  • Laurent Gorse

    Exactly what I was looking for. Rockin’

  • Ren

    Nope, the post actually has the best title ever since it leads me to this gold over here! Thanks!

  • jeff

    omg thank u

  • Edward P

    title is fine, thanks!