0

我想在运行时发现查询范围应该接收的参数数量。如何反映ActiveRecord范围

我tryed如下:

class Test < ActiveRecord::Base 
    scope :my_scope, Proc.new{ |q, x| 
     where("attr = ? and attrb = ?", q, x) 
    } 

    def self.my_scope_args 
     self.method(:my_scope).parameters 
    end 
end 

但调用

Test.my_scope_args 

返回[[:休息,:参数]]。如果我直接反映PROC对象上我获得所需的结果:

Proc.new{ |q, x| 
    where("attr = ? and attrb = ?", q, x) 
}.parameters 

返回[[:选择,:Q],[:选择,:X]]

有一种方法可以得到对范围的底层Proc对象的引用,以便我可以反思它?

回答

1

从细Active Record Query Interface Guide

14.1 Passing in arguments
[...]
Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects.

所以不是这样的:

scope :my_scope, Proc.new{ |q, x| 
    where("attr = ? and attrb = ?", q, x) 
} 

你应该这么说:

def self.my_scope(q, x) 
    where(:attr => q, :attrb => x) 
end 

然后你的my_scope_args将按预期工作。

+0

问题是当你想链接他们。 –

+0

或者试着做同样的事情作用域'def my_scope(x); all.scoping {“scope code goes here”};结束' –

+0

@IsmaelAbreu:那会是什么链接问题?当'scope1'和'scope2'是类方法时,你可以'M.scope1(x).scope2(y)'很好。 –