【问题标题】:How to check whether a model has a scope defined?如何检查模型是否定义了范围?
【发布时间】:2013-01-06 13:43:49
【问题描述】:
class Idea < ActiveRecord::Base
  attr_accessible :archived, :checked, :content, :note, :stared

  scope :stared, -> { where(stared: true) 
end

使用此代码,我如何测试Idea 上是否定义了范围(例如stared)。我想要这个效果

Idea.has_scope?(:stared) 
=> true
Idea.has_scope?(:unknown)
=> false

【问题讨论】:

    标签: ruby-on-rails model scope


    【解决方案1】:

    有一个方法:valid_scope_name 在内部也使用respond_to? + 也是一个受保护的方法 + 给出一个可怕的日志消息。它可以被调用为

    Idea.send(:valid_scope_name?,:stared)
    => true
    

    但这也将主要从 edgerails 中删除 - git commit

    【讨论】:

      【解决方案2】:

      你可以只使用 respond_to 吗?

      Idea.respond_to?(:stared)
      

      将产生真/假

      【讨论】:

      • 它将针对范围以外的所有实例方法进行测试。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多