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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With