I was wondering if there was a way to use ‘find_by_sql’ within a named_scope. I’d like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While you can put any SQL you like in the conditions of a named scope, if you then call
find_by_sqlthen the ‘scopes’ get thrown away.Given:
This works (it just sticks the SQL string in there – if you have more than one they get joined with AND)
However, this doesn’t
So the answer is ‘No’. If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together.
When you create normal queries, the
select,joins,conditions, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is howwith_scopeandnamed_scopework).With
find_by_sqlhowever, you just give rails a big string. It doesn’t know what goes where, so it’s not safe for it to go in and add the things it would need to add for the scopes to work.