Trying to do something pretty straightforward in a Rails controller. Right now, I am showing a user all results matching their user_id
from a Scoreboard table.
I now want to adjust that to show results from their user_id
but also only scores
greater than the integer 0. So I changed my controller to:
def index
@scoreboards = Scoreboard.where(user_id: current_user.id, "score >= 0").order(score: :desc)
end
This receives a syntax error, so my comparison in the .where
is probably wrong. How should I add this second condition?
I would try this:
@scoreboards = Scoreboard.where(user_id: current_user.id)
.where("category >= 0").order(score: :desc)
I try to avoid putting these kind of database operations directly in the controller, because the model is the more appropriate place. I'd write three scopes in the model:
class Scoreboard < ActiveRecord::Base
#...
scope :for_user_id, ->(user_id) { where(user_id: user_id) }
scope :with_scores, -> { where('score > 0') }
scope :by_descending_score, -> { order(score: :desc) }
#...
end
...then in the controller, you'd merely write this:
Scoreboard.for_user_id(current_user.id).with_scores.by_descending_score
This keeps your controller thinner (and more readable) while potentially supporting re-use of these lookups in the most atomic fashion and keeping the database logic wholly contained in the model.
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.