@english=Point.where(subject:English).order(subject_point:"DESC").first
@japanese=Point.where(subject:Japanese).order(subject_point:"DESC").first
All I can think of is to sort each subject in order of the highest score and extract the first data.
Is there a way to extract each subject at once without extracting it individually?
ActiveRecord hides SQL, but if you don't have knowledge of SQL, you don't know how to write it in ActiveRecord, or you write code that is typically considered a bad practice.After all, you need to know SQL and database knowledge.
If you just want a value, you can write it in SQL.
SELECT subject, max(subject_point) FROM points GROUP BY subject
This is what happens.It's very rudimentary in SQL.If you know this, you can think about how GROUP BY
and max
can be written in ActiveRecord, so
subject_points=Point.group(:subject).maximum(:subject_point)
subject_points ["english"]
You can see that it can be taken like this.
If you want to retrieve the entire record in the line that contains the maximum value, SQL itself becomes complicated, and writing this in ActiveRecord can be a pain.However, it is a kind of FAQ, so there is a lot of information.If you are interested, please check it out.
A typical bad practice is to loop the same query with different parameters.Based on SQL, you can't do loops (easily) in the first place, so you can think that there's something wrong with a code that turns in a loop.
© 2024 OneMinuteCode. All rights reserved.