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.

    tags\_tag.html.erb

    <%= link_to tag.name, tag_path(tag) %>
    

    posts\index.html.erb

    <%= 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.

    posts\index.html.erb

    <%= post.tags.map { |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á