Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord列表自定义作用域_Ruby On Rails_Ruby_Activerecord_Ruby On Rails 5 - Fatal编程技术网

Ruby on rails ActiveRecord列表自定义作用域

Ruby on rails ActiveRecord列表自定义作用域,ruby-on-rails,ruby,activerecord,ruby-on-rails-5,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 5,我想检查我的ActiveRecord类,看看它应用了哪些自定义作用域 class MyRecord < ActiveRecord::Base scope :custom_scope_one, ->() { where(id: 4) } scope :custom_scope_two, ->() { where(id: 4) } scope :custom_scope_three, ->() { where(id: 4) } end classmy

我想检查我的ActiveRecord类,看看它应用了哪些自定义作用域

class MyRecord < ActiveRecord::Base
    scope :custom_scope_one, ->() { where(id: 4) }
    scope :custom_scope_two, ->() { where(id: 4) }
    scope :custom_scope_three, ->() { where(id: 4) }
end
classmyrecord(){where(id:4)}
scope:custom_scope_two,->(){where(id:4)}
scope:custom_scope_three,->(){where(id:4)}
结束
所以我运行了一个类似于MyRecord.custom\u scopes的方法,它应该返回
[:custom\u scope\u one,:custom\u scope\u two,:custom\u scope\u three]

在rails 5中,它们是内置的吗?或者如何以编程方式实现这一点?

DSL助手只是创建了一个新方法,它不会将作用域名称存储在任何位置,因此不,它不可能开箱即用

OTOH,可以很容易地提供这样的功能:

ActiveRecord::Scoping::Named::ClassMethods.prepend(Module.new do
  def scope(name, body, &block)
    (@__scopes__ ||= []) << name
    super
  end
end)
您还可以为这个实例变量或任何东西声明一个访问器


注意:上面的代码没有经过测试,我只是证明了它看起来不错。

但是由于没有合理的方法来检测一个类方法是否真的是一个作用域,这将不会真正起作用。@muistooshort这将适用于原始问题中明确说明的示例:使用
scope
DSL声明的任何作用域都将被成功报告。
MyRecord.instance_variable_get(:@__scopes__)
#⇒ [:custom_scope_one, :custom_scope_two, :custom_scope_three]