0

I have 2 models Prize and Staff, One staff HAS_MANY prizes

I want to export noy only the prize, but also embedded the prize's owner (staff) in the JSON response.

How to do it ?

render json: Oj.dump( Prize.where(:staff_id => nil) )

Sample output (But not including the staff information)

{
can_accept_prize_now: true,
name: "Apple MacBook Pro Retina",
sn: 3,
}

Expected output

{
can_accept_prize_now: true,
name: "Apple MacBook Pro Retina",
sn: 3,
staff_id: 80,
staff_name: "Eric"
}
user3675188
  • 7,271
  • 11
  • 40
  • 76
  • Do we have has-to-many relation between this staff and prize ? like one staff can have many prizes ? then next question is, you want to get all attributes of prize in json response & from staff object you want the name only ? – Ajay Jan 13 '15 at 05:37

1 Answers1

0

You could probably could add something like the following to the Prize model:

def serializable_hash(options={})
  hash = super
  hash['staff_id'] = staff.id
  hash['staff_name'] = staff.name
  hash
end

If you're using ActiveModel::Serializers, you could probably do something like the following

class PrizeSerializer < ActiveModel::Serializer
  attributes :can_accept_prize_now, :name, :sn, :staff_id, :staff_name

  def staff_id
    object.staff.id
  end

  def staff_name
    object.staff.name
  end
end
Brad Pardee
  • 148
  • 1
  • 7