在rails中使用finder_sql的子查询

时间:2010-11-02 14:56:37

标签: ruby-on-rails

代码

has_many :open_invoices, :class_name => "ArInvHeader",
:finder_sql => 'SELECT ar_inv_headers.* FROM ar_inv_headers WHERE customer_id = #{id}  and
orig_amt = (select sum(amount) from ar_inv_actions,ar_inv_headers where ar_inv_actions.ar_inv_header_id = ar_inv_headers.id)'

我收到此错误。

ActiveRecord::StatementInvalid: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to y
our MySQL server version for the right syntax to use near ')' at line 1: SELECT COUNT(*) FROM ar_inv_actions,ar_inv_header
s where ar_inv_actions.ar_inv_header_id = ar_inv_headers.id)
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/abstract_adapter.rb:2
27:in `log'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/mysql_adapter.rb:324:
in `execute'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/mysql_adapter.rb:639:
in `select'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/abstract/database_sta
tements.rb:7:in `select_all_without_query_cache'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/abstract/query_cache.
rb:62:in `select_all'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/abstract/database_sta
tements.rb:13:in `select_one'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/connection_adapters/abstract/database_sta
tements.rb:19:in `select_value'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/base.rb:920:in `count_by_sql'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/associations/has_many_association.rb:34:i
n `count_records'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/associations/association_collection.rb:27
7:in `size'
    from C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.9/lib/active_record/associations/association_collection.rb:29
6:in `empty?'
    from (irb):9

2 个答案:

答案 0 :(得分:1)

看起来它正试图将你的finder_sql重新解释为counter_sql并且做得非常糟糕。解决方案是编写自己的counter_sql,它可以工作。

答案 1 :(得分:1)

我在ActiveRecord 3.2.12中看到的问题在CollectionAssociation#custom_counter_sql中,它通过将:finder_sql选项与此正则表达式匹配来将SELECT子句替换为COUNT(...):

/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im

匹配从“SELECT”到子查询中“FROM”的最后一次出现的所有内容,而不是您想要的第一个“FROM”。

最简单的解决方法是将自定义:counter_sql选项传递到has_manydocumented