Rails – 按照特定记录的下方排序并获取所有记录。

huangapple go评论49阅读模式
英文:

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 = &#39;year_3&#39;
sample_group = SampleGroup.find_by(year: year)
SampleGroup.where(&#39;position &lt;= ?&#39;, sample_group.position)

huangapple
  • 本文由 发表于 2023年7月23日 17:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定