Dan Tao
Dan Tao

Reputation: 128307

Can I select all attributes except for one in ActiveRecord?

Say I want to load a bunch of Foo records, but I only want to load the id and title attributes into memory:

foos = Foo.where([condition]).select('id, title')

What if I want to load all attributes EXCEPT for one (i.e. because it's giant text column)? You know, something like:

foos = Foo.where([condition]).select('* except giant_text_dump')

Obviously that doesn't work. But is there a way?

Upvotes: 3

Views: 2760

Answers (2)

Juanito Fatas
Juanito Fatas

Reputation: 9959

Like this?

Foo.where([condition]).select(*Foo.attribute_names.reject { |attr| attr == 'giant_text_dump' })

Upvotes: 6

Mori
Mori

Reputation: 27789

ActiveRecord doesn't have a way to do that built in, but you can do this:

fields = (Foo.attribute_names - ['giant_text_dump']).join(',')
Foo.where([condition]).select(fields)

Upvotes: 3

Related Questions