8
\$\begingroup\$

I use named scopes all over the place.

When I have a named scope that deals with two different tables, I tend to query the second table in a sub-query. That way, if I mix and match with other tables I don't need to worry about reusing a table alias or having ambiguous column names that only appear in bizarre scenarios.

For example, suppose I have a posts table that is one-to-many related to a tags table. I might add a with_tags scope on my Post model like this:

named_scope :with_tags, lambda { |tags|
 tags = [tags] if tags.kind_of? String
 {:conditions => ["id IN (SELECT post_id FROM tags WHERE name IN (?))", tags]}
}

However, that doesn't seem ideal. Many databases can use a join more efficiently than they can use a sub-query. A query that looks like this might perform better:

SELECT DISTINCT posts.* FROM posts JOIN tags ON posts.id = tags.post_id WHERE tags.name IN (?)

How do other people do this? Do you use the :include/:join parameters cleverly to know what the aliases ActiveRecord will use?

Phrancis
20.5k6 gold badges69 silver badges155 bronze badges
asked Feb 10, 2011 at 21:47
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You want to use what Rails calls eager loading. This is done with the :include parameter in your AR call. Add it to your lambda block.

SirPython
13.4k3 gold badges38 silver badges93 bronze badges
answered Mar 2, 2011 at 6:23
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.