Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full belongs_to object in json render?

Basically, I have an object that belongs_to :companies, and has the :company_id attribute. When I render json: @coupons, is it possible for the JSON to contain an attribute of its owner rather than the company_id?

like image 719
sgrif Avatar asked Sep 21 '11 20:09

sgrif


2 Answers

You might be able to do something like render :json => @coupons.to_json(:include => :company), at least it seems to have worked with my initial testing in rails 2.3.8.

Answer edited to use :include => :company rather than :include => :companies

like image 128
William Avatar answered Nov 10 '22 12:11

William


If you need to keep your json as compact as possible, it's best to use custom model methods to return only the data you need. I ended up adding a custom as_json method to the parent model and using the methods option to return subsets of the related object's data. Using include will include a full json serialization of the related model.

def as_json(options={})
  super(
    :only => [:id, :name],
    :methods => [
      :organization_type_name,
    ]
  )
end

def organization_type_name
  self.organization_type.name
end
like image 3
Tim Fletcher Avatar answered Nov 10 '22 14:11

Tim Fletcher