Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord select except columns

Tags:

Is there a way I can specify to select ALL columns in ActiveRecord except just a few. For example, for a User, I don't want to select their password hash or their email. Is this possible or do I have to manually hardcode all columns?

Thanks

like image 699
0xSina Avatar asked Jul 02 '13 16:07

0xSina


2 Answers

write a scope like

def select_without columns   select(column_names - columns.map(&:to_s)) end 
like image 55
Marian Theisen Avatar answered Sep 27 '22 22:09

Marian Theisen


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) 
like image 33
Aguardientico Avatar answered Sep 27 '22 22:09

Aguardientico