英文:
Rails - Sort and fetch all records below a particular record
问题
我想获取所有在给定年份之下的记录,例如:
如果给定年份是 year_3,则查询应该获取所有在 year_3 之下的记录,包括 year_3 在内。如何最好地实现这一目标?
英文:
I have a table called SampleGroup which will have a column year. the year can have values like below year_1, year_2 and so on
The SampleGroup table also has position which sorts the records based on year column. The table will always looks like this.
| year | position |
| -------- | -------------- |
| year_1 |0 |
| year_2 |1 |
| year_3 |2 |
| year_4 |3 |
I want to fetch all the records that are below a given year for eg:
If given year_3, the query should fetch all the records below year_3 and year_3 should be returned. What is the best way to achieve this?
答案1
得分: 1
首先获取匹配的记录,然后获取其下方的所有记录:
year = 'year_3'
sample_group = SampleGroup.find_by(year: year)
SampleGroup.where('position <= ?', sample_group.position)
英文:
I would achieve this with two queries. First fetch the matching record, then fetch all records positioned below it:
year = 'year_3'
sample_group = SampleGroup.find_by(year: year)
SampleGroup.where('position <= ?', sample_group.position)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论