ruby on rails - Formatting to_json method for child object -
i have rails object product:
{ id: 1 name: 'soup' } and customer object:
{ id: 20 name: 'ryans' } they linked via:
class product < activerecord::base belongs_to :customer when call product.to_json(methods: [:customer]), get:
{ id: 1 name: 'soup', customer: { id: 20 name: 'ryans' } } but need in format:
{ id: 1 name: 'soup', customer_name: 'ryans' } is possible? i'm using rails v4.1.7
you can delegate nameto customer class
class product < activerecord::base belongs_to :customer delegate :name, to: :customer, prefix: true you can do
product.to_json(methods: [:customer_name])
Comments
Post a Comment