显示rails中范围的结果

时间:2014-12-16 19:56:47

标签: ruby-on-rails view model

我正在处理具有模型Exercise的应用程序,并且我添加了下面显示的三个范围方法:

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

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

1 个答案:

答案 0 :(得分: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

然后转到&#34; / exercise?hard = true&#34;