【问题标题】:Slimming up scoped filters in rails controller在 Rails 控制器中缩小范围过滤器
【发布时间】:2014-02-23 17:38:28
【问题描述】:

我将过滤功能放入应用程序(Rails 4.1beta) - 我通过在 Item 模型上创建范围、通过请求参数传递范围并在索引操作中执行 case 语句来做到这一点。一切正常,但我正试图在其中一个控制器的索引操作中消除代码异味;

def index                    
  case params[:scope]        
    when "recent"            
      @items = Item.recent
    when "active"
      @items = Item.active
    when "inactive"
      @items = Item.inactive
    else
      @items = Item.all
  end
end 

感觉有点太死板/冗长了。我真的很想做这样的事情;

def index
  @items = Item.send(params[:scope])
end

然后我让应用程序对调用 Item 类的方法的人敞开大门。那里的恶劣条件有点违背了我想要实现的目标。

我是否缺少一些可以帮助我的 Rails 魔法?

【问题讨论】:

    标签: ruby-on-rails controller scope


    【解决方案1】:

    您可以使用不同的控制器来执行这些操作。

    inactive_items_controller.rb

    def index
      @items = Item.inactive
    end
    

    recent_items_controller.rb

    def index
      @items = Item.recent
    end
    

    等等

    或者您可以将上面的逻辑移到模型中

    物品模型

    def self.custom_scope(scope)
      case scope   
      when "recent"            
        Item.recent
      when "active"
        Item.active
      when "inactive"
        Item.inactive
      else
        Item.all
      end
    end
    

    def self.custom_scope(scope)
      recent   if scope == 'recent'
      active   if scope == 'active'
      inactive if scope == 'inactive'
      scoped   if scope.blank?
    end
    

    然后在你的索引中

    @items = Item.custom_scope params[:scope]
    

    【讨论】:

      【解决方案2】:

      类似这样的:

      if ['recent', 'active', 'inactive'].include?(params[:scope])
        @items = Item.send(params[:scope])
      else
        @items = Item.all
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-12
        • 2014-01-05
        • 2018-12-12
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        相关资源
        最近更新 更多