user1764536
user1764536

Reputation: 11

Ruby & Activerecord - Working with query results

I need help. I'm optimizing Ruby project. There are a lot of single queries so I read them at once with array of ids, example:

projects = Project.find_by_id(array_of_ids)

And I got significant improvement in speed. But the problem is when I want to search in such result, how can I work with such result?

p = projects .find{ |project| project.id==pr.id } # doesn't work

Can I convert 'projects' to array or use active-record methods further on it? Can I get two-dimensional array of 'projects' grouped by some parameter using Activerecord?

Upvotes: 1

Views: 406

Answers (2)

alexpls
alexpls

Reputation: 1964

You'd need to use the scoped_by_* method instead of find_by_* if you wanted to return an ActiveRecord::Relation object (that you can do further SQL queries on) instead of an Array.

An explanation of scoped_by_* can be found here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Here's what your code should look like if you were using scoped_by_*.

projects = Project.scoped_by_id(array_of_ids)
p = projects.find(pr.id)

Upvotes: 1

Viren
Viren

Reputation: 5962

There are couple of thing you are missing over here

a) projects = Project.find_by_id(array_of_ids)

will give only one result

to get and array you need to fire query like this

a) projects = Project.find_all_by_id(array_of_ids)

Which Version of Rails are you using if Rails 3+ that what you want can be easily done with arel

 b) projects = Project.where("id in (?)",array_of_ids)

Now this would give you a relation object and you can chain your furthur query on it

If you are using Rails 2.3+ it would be better to do this using named_scope or lambda

Hope this help

Upvotes: 0

Related Questions