将SQL封装在named_scope中

问题描述:

我想知道是否有方法在named_scope中使用“find_by_sql”。我想将自定义sql视为named_scope,以便将其链接到我现有的named_scopes。这对于优化我经常使用的sql代码片段也是很好的。将SQL封装在named_scope中

虽然你可以把你在一个名为范围的条件,喜欢的任何SQL,如果你再打电话find_by_sql那么“范围'扔掉。

考虑:

class Item 
    # Anything you can put in an sql WHERE you can put here 
    named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' 
end 

这工作(只是粘SQL字符串中有 - 如果你有一个比他们更得到与加盟AND)

Item.mine.find :all 
=> SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1) 

然而,这并不

Items.mine.find_by_sql 'select * from items limit 1' 
=> select * from items limit 1 

所以答案是“否”。如果你想到幕后发生了什么,那么这很有道理。为了构建SQL rails必须知道它如何组合在一起。
当您创建正常查询时,select,joins,conditions等都被分解为不同的部分。 Rails知道它可以将条件添加到条件中,而不会影响其他所有条件(这是with_scopenamed_scope的工作方式)。

然而,find_by_sql然而,你只是给铁轨一大串。它不知道什么地方在哪里,因此它不适合进入并添加它需要添加的范围才能工作。

知道为什么不

:named_scope:条件=> [您的SQL]

这并不是完全解决您问到的问题,但您可能会调查'contruct_finder_sql'。它使您可以获取命名作用域的SQL。

named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' 
named_scope :additional { 
    :condtions => mine.send(:construct_finder_sql,{}) + " additional = 'foo'" 
}