Reputation: 113
I wanted to overwrite the default active-record attributes
method because i dont want to return created_at
and updated_at
in my json responses of any model.
so here's what i have done.
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def attributes
super.except('created_at', 'updated_at')
end
end
This worked fine for me for the past few months. But now i came across a scenario that i should not send the password
attribute from my User
model. So
class User < ApplicationRecord
def attributes
super.except('password')
end
end
This worked like a charm when i run it from rails console. But when i run it from a controller, i really don't know for what reason, but it goes for a infinite loop. And here is my controller action.
def update
@object = klass.find(id)
@object.update_attributes!(update_params)
render json: {
status: true,
message: 'Saved Successfully..!',
data: object_json(@object)
}
end
def object_json(object)
object.as_json.except('updated_at', 'created_at')
end
Can someone help me out of this.
Upvotes: 0
Views: 974
Reputation: 198
A better way to control what attributes you want to render in your JSON responses, is to use a serializer like for example active_model_serializers
A good article to read about it can be found here SERVING CUSTOM JSON
I wouldn't recommend overwriting default active-record attributes
method
Upvotes: 2