To select specific fields for the result of a query, you can use the select
method:
Client.select(:name)
This returns a relation of Clients where the name
is the only field initialized.
I'd like to select all fields, except for the ones I specify. Exactly like select, but the inverse.
Client.select(name: false) # Hypothetical! Not real!
The above hypothetical would return a relation of Clients with all fields initialized, except the name
.
Obviously, that hypothetical example does not work. Is there anything that would?
Constraints: I'd like to do this entirely within the domain of the ActiveRecord/SQL — I do not want to convert to Ruby arrays or hashes.
Thanks!
You could use:
Client.select(Client.column_names - ["name", "some_other_column"])
Edit: Rails 5 also introduced ignored_columns
if you want to exclude columns by default.
https://github.com/rails/rails/pull/21720 https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-ignored_columns-3D
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