cbrulak
cbrulak

Reputation: 15629

Rails: Getting an array of object ids by query/conversion (for comparision)

Basically, I want an array of ids from the database.

Some background:

I assumed that getting an array of ids would be much more efficient than querying the database for each instance of foo when rendering the foo list with checkboxes.

Ideas? Apologies in advance if this is not clear.

Upvotes: 5

Views: 12804

Answers (5)

Rohit Yerramsetty
Rohit Yerramsetty

Reputation: 17

array1 = User.all.collect(&:id)

The array1 has the values of all the ids in the table Users.

Upvotes: 1

Mitch
Mitch

Reputation: 239

More recent versions of Rails support Model.pluck(:field_name)

Upvotes: 8

Jyothu
Jyothu

Reputation: 3144

we can use the map method also this way

Model.all.map(&:field_name)

Upvotes: 14

cbrulak
cbrulak

Reputation: 15629

I used the map method:

@bars = Bar.all(:select => bar.id)
@bars = @bars.map{|bar| bar.id}

Then I end up with array of ids. And only one query.

Upvotes: 7

Nikita Rybak
Nikita Rybak

Reputation: 68006

What's the problem, than? If you have rails has_many or has_and_belongs_to_many association, rails will fetch ids for you. See relevant tutorial for details, in short it's like @order_ids = @customer.order_ids.

Otherwise, you can easily use plain sql (or active record query).

Upvotes: 0

Related Questions