So, an Object has many properties and a property belongs to an Object. That's currently the association. Now when I render all the objects, using Object.all and include the :properties associations, I get all the attributes of the property model in the rendered JSON. But I really don't need that. All I need is the number of associations there are. I.e., just the number of properties there are associated with any one object. Here is my code:
@objects = Object.all
respond_to do |format|
format.json {
render json: @objects.to_json(:include => [:properties])
}
end
This yields something like this. There is currently only 1 property associated with the 1 existing object, and as you can see in the JSON, I'm getting a lot of information about the associated properties, (or rather, property) that I don't need nor want.
"id": 2,
"attrs_go_here": "asdfsdaf"
"created_at": "2018-07-14T23:51:55.161Z",
"updated_at": "2018-07-14T23:51:55.161Z",
"properties": [
{
"id": 5,
"more_attributes": "asdfasdfasdf"
"created_at": "2018-07-14T23:53:14.917Z",
"updated_at": "2018-07-14T23:53:14.917Z"
}
]
But instead, I want something like this, where I get the number of associations:
"id": 2,
"attrs_go_here": "asdfsdaf"
"created_at": "2018-07-14T23:51:55.161Z",
"updated_at": "2018-07-14T23:51:55.161Z",
"properties": 1
My reasoning for only wanting the number is because there could potentially be hundreds of thousands of properties associated with any one object. And I feel like it would be really slow to render ALL the attributes of ALL the properties associated with an object when all I need is the number of associations there are between an object and its properties in the first place.
Add a method to you model Object
def properties_count
self.properties.count
end
And on you controller do
render json: @objects.to_json(methods: [:properties_count])
Although I am not sure about a possible n+1. In case of that you should use
@objects = Object.includes(:properties).all
Edit
Technically its not intended to give arguments to_json only takes getters. But you could do something along those lines:
class Object
attr_accessor :attribute
def method_with_params(attribute = nil)
attribute ||= attribute
# rest of your code
end
end
@object.attribute = 'foodbar'
render json: @object.to_json(methods: [:method_with_params]
)
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