本文介绍了在Rails中显示示波器的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on application which has model Exercise and I added the three scopes method shown below:

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

,我有一个视图,我希望在其中显示内容取决于我使用的方法.例如,如果我单击链接"easy",它将显示数据库中所有容易的练习,依此类推.但是我不知道如何开始.

and I have a view where I want display content depends onto which method I've used. For instance, if I click on link "easy", it should show all exercises in the database which are easy and so on. But I have any idea how to start.

推荐答案

请考虑一下.经典的,由脚手架生成的索引方法可以做到这一点:

Think about this. The classic, scaffold generated index method, does this:

def index
  @exercises = Exercise.all
end

但是您需要调用其中之一

But you need to call one of these instead

Exercise.easy
Exercise.medium
Exercise.hard

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

You can modify index method to do this:

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",或者进入锻炼索引所在的任何位置.如果您了解发生了什么,可以使用 has_scope 这个gem,将问题减少到这个程度: /p>

Then you go to "/exercies?scope=easy", or wherever your exercises index is at. If you get to understand what is happening you can use this gem has_scope, which reduces the problem to this:

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"

Then go to "/exercises?hard=true"

这篇关于在Rails中显示示波器的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:56