How to Extract a Specified Record in ActiveRecord

Asked 1 years ago, Updated 1 years ago, 129 views

Current situation/what you want to realize

I would like to ask you a question regarding the captioned matter.
】What I want to realize したい

(I want to win first place in each composition)

[Current situation]
Currently, DB has items and compositions tables.
Columns and stored data are as follows:
Enter a description of the image here
Enter a description of the image here

○ In the items table, there are points that the item has.
○The items table has a competiton_id that specifies which competition it belongs to.

Tried

Item.maximum("points")
I want to output a record just because the maximum value is output.
Item.order("points DESC")
Ungrouped and retrieved in descending order of points
Item.order("points DESC").group(:composition_id) 
You got the first record of compilation_id instead of the highest record of points (desired result)

I tried many things, but I can't extract it as I want.
I would appreciate it if you could let me know the ActiveRecord to extract the above records.

Supplementary information (for example, FW/Tool Version)

  • ruby2.7.0p0
  • Rails 6.1.0
  • sqlite

ruby-on-rails rails-activerecord

2022-09-30 20:24

1 Answers

Self-resolved as follows

query="SELECT*,MAX(points) FROM Items GROUP BY composition_id"

@winners=Item.find_by_sql(query)


2022-09-30 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.