我正在尝试<%= @user.challenges.habit_badge.count %>
,但我不知道如何让范围工作以包含我希望包含在name
计数中的多个habit_badge
字符串
scope :habit_badge, -> do
where(name: ('Read 20 Min', 'Run a Mile', 'Meditate 10 Min', etc....))
end
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")
else
ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star")
end
end
答案 0 :(得分:2)
将一系列名称传递给范围:
scope :habit_badge, -> {
where(name: ['Read 20 Min', 'Run a Mile', 'Meditate 10 Min'])
}
它将被视为:
SELECT "resources".* FROM "resources" WHERE "resources"."name" IN ('Read 20 Min', 'Run a Mile', 'Meditate 10 Min')