简体   繁体   中英

Displaying results from scopes in rails

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") }

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

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

Then go to "/exercises?hard=true"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM