我想知道是否有办法使用“find_by_sql”在named_scope中。我想将自定义sql视为named_scope,因此我可以将其链接到我现有的named_scopes。优化我经常使用的sql片段也很有用。

有帮助吗?

解决方案

虽然您可以在命名范围的条件下放置任何您喜欢的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 join conditions 等都被分解成不同的部分。 Rails知道它可以在不影响其他条件的情况下添加条件(这是 with_scope named_scope 的工作方式)。

但是,使用 find_by_sql ,你只需给rails一个大字符串。它不知道究竟发生了什么,所以它进入并添加为示波器添加所需的东西是不安全的。

其他提示

这并不能完全解决您的问题,但您可能会调查'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'"
}

确定为什么不

:named_scope:conditions => [你的sql]

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top