ActiveRecord select except columns

Something like this?

exclude_columns = ['password', 'email']
columns = User.attribute_names.delete_if { |x| exclude_columns.include?(x) }

User.select(columns)

EDIT

I forgot that we can do Array1 - Array2

A best answer:

exclude_columns = ['password', 'email']
columns = User.attribute_names - exclude_columns

User.select(columns)

Another really usefull way it's with a scope inside the model in case you need to avoid a column constantly.

In my case I save images into blob fields so I want to avoid those to be loaded everytime and in a easy way:

scope :select_exclude_image, ->  { select( Movie.attribute_names - ['image'] ) }

Then to avoid the image in the selection you can do something like that:

Movie.select_exclude_image.first

or

Movie.select_exclude_image.all

I hope it will help!


write a scope like

def select_without columns
  select(column_names - columns.map(&:to_s))
end