【问题标题】:Displaying results from scopes in rails在 rails 中显示范围的结果
【发布时间】:2014-12-16 19:56:47
【问题描述】:

我正在开发具有模型Exercise 的应用程序,并添加了如下所示的三个作用域方法:

scope :easy, -> { where(level: "easy") }
scope :medium, -> { where(level: "medium") }
scope :hard, -> { where(level: "hard") }

我有一个视图,我希望在哪里显示内容取决于我使用的方法。例如,如果我点击链接“easy”,它应该会显示数据库中所有简单的练习等等。但我知道如何开始。

【问题讨论】:

    标签: ruby-on-rails view model


    【解决方案1】:

    考虑一下。经典的脚手架生成索引方法是这样做的:

    def index
      @exercises = Exercise.all
    end
    

    但您需要改为调用其中之一

    Exercise.easy
    Exercise.medium
    Exercise.hard
    

    您可以修改索引方法来做到这一点:

    SCOPES = %w|easy medium hard|
    
    def index
      @exercices = if params[:scope].present? && SCOPES.include?(params[:scope])
        Exercise.public_send(params[:scope])
      else
        Exercise.all
      end
    end
    

    然后您转到“/exercies?scope=easy”,或者您的练习索引所在的任何位置。如果您了解正在发生的事情,您可以使用此 gem has_scope,它将问题简化为:

    class ExercisesController < ApplicationController
      has_scope :easy,   type: :boolean
      has_scope :medium, type: :boolean
      has_scope :hard,   type: :boolean
    
      def index
        @exercises = apply_scopes(Exercise)
      end
    end
    

    然后转到“/exercises?hard=true”

    【讨论】:

    • 听起来很不错,但我尝试使用 has_scope 并给出了这个错误:Unknown key: :boolean. Valid keys are: :type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank。编辑我正在使用 Rails 4.2.0.rc1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    相关资源
    最近更新 更多