10

How do you select multiple fields with distinct values, and other non-distinct fields with them, all in one call with where and limit? I tried .pluck (which supports multiple fields in rails 4), .uniq (which didn't work in my case).

2 Answers 2

22

This is what worked for me, when used in the controller action

@models = Model.select('DISTINCT ON (field1,field2,field3) *')
     .where(id: params[:id])
     .limit(100)
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a bit less verbose and more ActiveRecord-centered approach which should work not only for Postgres but for MySQL as well.

Model.select('field1,field2').distinct.where(field3: 'value').limit(10)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.