Search code examples
ruby-on-railsjbuilder

Merging one attribute for all records into array using Jbuilder


I have a collection of products, each has_many tags. I'd like to combine the name of all tags so that I have an array of all tag names.

Desired Output:

{
    "title": "Product1", 
    "tags": ["name1", "name2", "name3"]
}

My current jbuilder is giving me:

{Products: [{
    "title": "Product1",
    "tags":[
        {"tag1":
           {"name": "name1"}
         },
        {"tag2": 
           {"name": "name2"}
         },
        {"tag3":
           {"name": "name3"}
         }
      ]
}]}

My current jbuilder.

json.array! @products do |product|
    json.title product.title
    json.tags product.tags do |tag|
        json.name tag.name
    end
end

Thanks for your help!


Solution

  • Just extract the tag name from each tag!

    json.array! @products do |product|
        json.title product.title
        json.tags product.tags.map(&:name)
    end
    

    If tag is a relation, you can make this even more efficient using pluck instead

    json.array! @products do |product|
        json.title product.title
        json.tags product.tags.pluck(:name)
    end