ivanreese
ivanreese

Reputation: 2758

Specify fields to exclude from Rails query result

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!

Upvotes: 7

Views: 4639

Answers (1)

David Aldridge
David Aldridge

Reputation: 52336

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

Upvotes: 13

Related Questions