Reputation: 15629
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
Reputation: 17
array1 = User.all.collect(&:id)
The array1
has the values of all the ids in the table Users
.
Upvotes: 1
Reputation: 3144
we can use the map method also this way
Model.all.map(&:field_name)
Upvotes: 14
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
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