Search code examples
ruby-on-railsrubyjsonrabl

Ruby map JSON multiple but not all attributes with RABL


I have the following Rabl in my views:

node(:relations) do |p|
  related = p.relations.pluck(:related_to_id)
  Spree::Product.find(related)
end

This renders the following:

"relations": [
{
"product": {
"id": 2,
"name": "T-SHIRT",
"description": "Awesome T shirts"
"created_at": "..."
"updated_at: "..."
 .
 .
 .
 bunch of other columns that I don't need. 

My question is how do I only grab :name and :description, so that the JSON output looks like:

"relations": [
    {
    "product": {
    "name": "T-SHIRT",
    "description": "Awesome T shirts"
    }
 ]

I've tried mapping it, Spree::Product.find(related).map { |r| [r.name, r.description] }

But that returns only the values, like so:

"relations": [
"T-SHIRT",
"Awesome T shirts"
]

Thank you for your help!

UPDATE:

When I write:

child :related_products do
  attributes :name, :description
end

I get:

"spree_relations": [
{}
]

Link to model:

https://github.com/spree-contrib/spree_related_products/blob/master/app/models/spree/relation.rb


Solution

  • Well, there probably multiple ways to do it.

    You can use rails #as_json method.

    node(:relations) do |p|
      related = p.relations.pluck(:related_to_id)
      Spree::Product.find(related).as_json(only: [:name, :description])
    end
    

    Or you can try to do it the rabl way.

    child :related_products do
      attributes :name, :description
    end
    

    But for this you might need to change your model a bit.