How to remove id from select active record?
Asked Answered
S

2

8

Query on console

User.select('email','dob')

returns,

[#<User:0x000000084a9b08 id: nil, email: "[email protected]">,

Why am I getting id attributes in rails 4? How to get rid of this?

Sophiasophie answered 28/10, 2015 at 12:27 Comment(0)
L
2

This will give you desired output

User.pluck(:email, :dob)
Leanaleanard answered 30/10, 2015 at 8:43 Comment(0)
C
39

Pluck only returns the values if you want keys and values then try this:

User.select('email','dob').as_json(:except => :id) In my case the desired result was a JSON object. So, inside the as_json method you can exclude any column you desire

(additionally you can invoke object methods or access associated tables as well)

Cathiecathleen answered 31/10, 2016 at 19:2 Comment(2)
Most flexible answer, works for aggregations as wellTeishateixeira
This answer solved for me. It would be awesome if there was an unselect() method for better readability, or if select() accepted arguments prepended with - to indicate they're not wanted. as_json feels more to do with the format (rather than the contents) of the data.Mitzi
L
2

This will give you desired output

User.pluck(:email, :dob)
Leanaleanard answered 30/10, 2015 at 8:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.