stack twitter tryhackme rss linkedin cross

Wilco van Esch

Skip to main content

Search results

    Render comma-separated partials for an array of objects in Rails

    Say you have Posts which have Tags associated with them. In the Post index view you display all Posts, with the Tags for each.

    Title: Cities of Africa
    Tags: Cape TownFesNairobiKigaliKhartoum
    Title: Cities of South America
    Tags: Buenos AiresRio de JaneiroQuitoSantiagoBogot√°

    You'll notice a problem here. All the tags are listed without any kind of separation. The reason is because in the view we are rendering a partial for each tag whereby each partial simply lists and links the tag name, and these are then listed out.


    <%= link_to, tag_path(tag) %>


    <%= render post.tags %>

    To solve this problem, We can't just join the tags through render post.tags.join(", "). That would make Rails look for a partial by the name of our joined tags. It would work without the partials through post.tags.join(", "), but to keep using our partial we need to join the tags separately per post.


    <%= { |t| render t }.join(", ").html_safe %>

    This gives us a nicely comma-separated list, whilst maintaining the tag links.

    Title: Cities of Africa
    Tags: Cape Town, Fes, Nairobi, Kigali, Khartoum
    Title: Cities of South America
    Tags: Buenos Aires, Rio de Janeiro, Quito, Santiago, Bogot√°