1

How can I filter first n records based on a specific column? For example, the column name in Recommendation?

if the name of record 1 and 2 were both Dave, record 1 and 3 would be returned and not record 2.

Recommendation.where(id: [1,2,3,4]).limit(2)`

I tried to use distinct but it appears you need to also use pluck which I'd rather not do because I'd like the object.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
user2954587
  • 4,661
  • 6
  • 43
  • 101
  • Assuming you have a somewhat large dataset, you probably want to do this at the database layer. First you need to learn what query you need for your database, and then you need to learn how to execute such a query from Rails. For the first part, this is a good starting point: https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group – Nathan Apr 17 '18 at 23:34

1 Answers1

0

You can chain an additional where, which would ask with AND for the name attribute and use distinct asking for uniqueness on the name attribute.

Recommendation.select('DISTINCT(name)')
              .where(id: [1, 2, 3, ...])
              .where('name = ?', name)
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59