Reputation: 572
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.
Upvotes: 0
Views: 73
Reputation: 7725
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"
Upvotes: 1