Roger Gonzalez Roger Gonzalez - 6 months ago 12
Ruby Question

How can I add a new attribute from another table to a serializer?

I have the following tables:

Table1
:name
:resource

Table2
:FK Table1
:FK Other Table
:quantity


And the following serializer

class Table1 < ActiveModel::Serializer
attributes :id,
:name,
:resource
end


What I need is that the serializer returns all its attributes and the
quantity
from
Table2
, where it has a relationship.

Any help would be appreciated.

Answer

ActiveModel::Serializer actually supports this, here is my example

class Table1Serializer < ActiveModel::Serializer
  attributes :id, :name, :resource
  has_one :table_2, serializer: Table2Serializer
end

class Table2Serializer < ActiveModel::Serializer
  attributes :id, :quantity
end

So you just specify the relation with the corresponding serializer it will work, btw I use Table1Serializer instead of Table1 to avoid misunderstanding with Table1 (model)

Another option is, if you don't want to write the Table2Serializer, you can use custom attribute, it is like:

class Table1Serializer < ActiveModel::Serializer
   attributes :id, :name, :resource
   attributes :table_2

   def table_2
     object.table_2
   end
end

So 2 ways you can apply, but for relation like you mentioned, I prefer the first option, because I may use Table2Serializer later!

Comments