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'm rendering a list of objets (foos) to the user with a checkbox.
- If the user checks the box a row is create in a different table (bar)
- when rendering the foo list + checkbox I want to check if the unique id any given foo already exists in the bar id array.
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开发者_JAVA技巧? Apologies in advance if this is not clear.
we can use the map method also this way
Model.all.map(&:field_name)
More recent versions of Rails support Model.pluck(:field_name)
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.
array1 = User.all.collect(&:id)
The array1
has the values of all the ids in the table Users
.
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).
精彩评论