I'm using the to_json
method on my model object that I created by doing something like:
user = User.find(1)
When I do user.to_json
, a lot of attributes are missing, including user.id
from the encoded JSON string. It appears that all of the attributes that I've added as attr_accessible from the User model are there, but none of the others. Perhaps that is what to_json is doing, but I think that adding id
to attr_accessible is a no go.
What is the right way of solving this problem?
UPDATE
This looks to be a specific issue with Devise. If I comment out the following from user.rb, everything works as expected:
devise :rememberable, :trackable, :token_authenticatable, :omniauthable
I haven't checked but I believe Devise does that for you; it includes only certain attributes via attr_accessible.
In any case the right way to solve this is to override the as_json
method like so:
def as_json(options = nil)
{
my_attr: my_attr,
etc: etc
}
end
It's a simple hash and it's a really powerful method to generate JSON in AR, without messing with the to_json
method.
By default Devise overrides the serializable_hash method to expose only accessible attributes (so things like the encrypted_password doesn't get serialized by default on APIs).
You could try to override this method and add the auth_token to the hash, something like this:
def serializable_hash(options = nil) super(options).merge("auth_token" => auth_token) 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