- 4 months ago 25
Ruby Question

scope count multiple string names?

I'm trying to do

<%= @user.challenges.habit_badge.count %>
, but I don't know how I can get the scope to work to include multiple
strings I want to include in the

scope :habit_badge, -> do
where(name: ('Read 20 Min', 'Run a Mile', 'Meditate 10 Min', etc....))

def habit_badge
if name == "Read 20 Min"
ActionController::Base.helpers.image_tag("read.png", class: "gold-star")
elsif name == "Exercise 20 Min"
ActionController::Base.helpers.image_tag("exercise.png", class: "gold-star")
elsif name == "Meditate 10 Min"
ActionController::Base.helpers.image_tag("meditate.png", class: "gold-star")
elsif name == "Stretch 5 Min"
ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star")
elsif name == "Write 500 Words"
ActionController::Base.helpers.image_tag("write.png", class: "gold-star")
elsif name == "Walk 5,000 Steps"
ActionController::Base.helpers.image_tag("walk.png", class: "gold-star")
elsif name == "Eat Fruit & Veg"
ActionController::Base.helpers.image_tag("fruit-and-vegetable.png", class: "gold-star")
elsif name == "Plan Day"
ActionController::Base.helpers.image_tag("plan.png", class: "gold-star")
elsif name == "After Waking, Guzzle Water"
ActionController::Base.helpers.image_tag("water.png", class: "gold-star")
elsif name == "Track Consumption"
ActionController::Base.helpers.image_tag("track-food.png", class: "gold-star")
elsif name == "Random Act of Kindness"
ActionController::Base.helpers.image_tag("random-kindness.png", class: "gold-star")
elsif name == "Write 3 Gratitudes"
ActionController::Base.helpers.image_tag("gratitude.png", class: "gold-star")
elsif name == "Juice Fast"
ActionController::Base.helpers.image_tag("juice.png", class: "gold-star")
elsif name == "Not Smoke"
ActionController::Base.helpers.image_tag("not-smoke.png", class: "gold-star")
elsif name == "Not Drink Alcohol"
ActionController::Base.helpers.image_tag("not-drink.png", class: "gold-star")
ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star")


Pass an array of names to scope:

scope :habit_badge, -> {
  where(name: ['Read 20 Min', 'Run a Mile', 'Meditate 10 Min'])

It will be treated as:

SELECT "resources".* FROM "resources" WHERE "resources"."name" IN ('Read 20 Min', 'Run a Mile', 'Meditate 10 Min')