I am receiving a set of models from my SQLite Database with Ruby on Rails 2.3.5. Currently I am using a subquery in order to select only the ones which I really want to have:
find(:all,
:conditions => "foo.id in (
SELECT bar.foo_id FROM bar
JOIN baz
ON baz.bar_id = bar.id
WHERE baz.bla in (1, 2, 3)
)"
)
I know this is stupid, because the subquery evaluates the same result for every row and I guess SQLite is not smart enough to notice that it could be optimized. So I would like to take it out of the query. I know that I could simply call it from Rails using a second find(), but given that the return value of the subquery may become relatively big, I would like to do everything in the database, so I don’t need to juggle huge data between the Database and Rails.
So, how can I do the Model’s find() and tell it, that it should look up the return value of my actual subquery and then use it’s result for the comparison of my other rows? Can I pass this in one call of find() into SQLite?
I wonder if you could do something like the following:
Which is what I’d try to rewrite it to in Rails 3.