Mark Mark - 4 months ago 8
Ruby Question

Formatting to_json method for child object

I have a Rails object Product:

{
id: 1
name: 'soup'
}


And a Customer object:

{
id: 20
name: 'Ryans'
}


They are linked via:

class Product < ActiveRecord::Base
belongs_to :customer


When I call Product.to_json(methods: [:customer]), I get:

{
id: 1
name: 'soup',
customer: {
id: 20
name: 'Ryans'
}
}


But I need this to be in the format:

{
id: 1
name: 'soup',
customer_name: 'Ryans'
}


Is this possible? I'm using Rails v4.1.7

Answer

You can delegate nameto your Customer class

class Product < ActiveRecord::Base
  belongs_to :customer
  delegate :name, to: :customer, prefix: true

You can then do

Product.to_json(methods: [:customer_name])