I want to do something a bit like –
@apples = Fruit.find :all, :conditions => ["type = ?", "apple"]
@pears = Fruit.find :all, :conditions => ["type = ?", "pear"]
@tomatos = Fruit.find :all, :conditions => ["type = ?", "tomato"]
The problem is this takes 3 DB requests. Is there a way to combine these so it only makes 1 request but gets all the required info?
Thanks,
Alex
Like said already in the comment, running a big query and fetching all entries and then selecting them via Ruby can be a pain in the ass. There a few reasons to let MySQL (or whatever database you are using) do the job:
If you have 1 million entries, Ruby have to instantiate 1 million ActiveRecord objects. This eats up memory very fast, and can make your application unusable, especially in production. Imagine 100 users accessing your site, and each of your dynos (hopefully you have more than one) has to load 1 million entries and compare 1 million strings!
Let the database do their jobs. They like their jobs, and they are really good at it. In fact they are optimized to run such queries. If your database seems to be slow, check your indices and tweak them if necessary.
It makes your code ugly and maybe even unreadable having a big query and then splitting it up, instead of 3 variables, each defined and fetched in it’s own row.