Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 708
ivanreese Avatar asked Dec 05 '15 20:12

ivanreese


Video Answer


1 Answers

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

like image 91
David Aldridge Avatar answered Nov 09 '22 23:11

David Aldridge