Question

A query like this:

User.where(username:'myuser').select(:created_at).first.to_json

Returns JSON like this: {\"created_at\":\"2014-03-01 18:03:00\",\"id\":null}

Why is there an "id" field in the generated JSON? Is there an easy way to get rid of it? I don't want to use :pluck because I need the field labels in the returned data structure.

Was it helpful?

Solution

I think it might have been a change in Rails 4 where a query like User.where(username:'myuser').select(:created_at).first will include the id value even though it wasn't a part of the select. You can exclude it with:

User.where(username:'myuser').select(:created_at).first.to_json(except: :id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top