How to return an object with an ids arrangement in a ruby on rails has_and_belongs_to_many

-1

I hope you can help me, I have the following models

class Family < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Category < ApplicationRecord
  has_and_belongs_to_many :families
end

and I need to return an object like the following

{
 id: 1
 descripcion: 'Ejemplo',
 categories: [1,2,3,4]
}

where the main object belongs to Family, try with include but I return an array of Category objects and it's not what I need, what I need is the arrangement of ids, I searched and found nothing, I hope someone knows how to do it please

    
asked by Cesar Hernández 06.04.2018 в 19:56
source

1 answer

1

You can use the as_json method directly on the result of your model, along with the parameters include and except ; for example:

Family.first.as_json(include: :categories, except: :created_at, :updated_at)

Result:

{
  id: 1
  descripcion: 'Ejemplo',
  categories: [
    { id: 1, descripcion: "category 1", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00" },
    { id: 2, descripcion: "category 2", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00"  },
    { id: 3, descripcion: "category 3", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00"  },
    { id: 4, descripcion: "category 4", created_at: "2018-01-01T00:00:00", updated_at: "2018-01-01T00:00:00"  }
  ]
}

include indicates the associations you want to include and except indicate the columns to be omitted from the base object (i.e. Family ); with that result you could then read only the id of each category, or, you could indicate that it only brings you the id :

Family.first.as_json(include: [categories: { only: :id }], except: :created_at, :updated_at)

Result:

{
  id: 1
  descripcion: 'Ejemplo',
  categories: [
    { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }
  ]
}

This is the simplest form, however you could not generate the arrangement with the id as you specify in your question; If you need that option, then I would recommend using jBuilder or ActiveModel Serializer .

    
answered by 06.04.2018 в 23:06