1

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.