Chris
Chris

Reputation: 12191

Get models with distinct attribute ActiveRecord

I have a bunch of records in my database which all have the same Title but different Locations. Once I filter by within a location boundary, I want to filter out ones with the same Title. Is there an ActiveRecord way to do this? I know about select, but that will only return titles, and I actually need the entire record.

So I have a Business which has a Title. If I select all of the businesses within a given lat/long boundary, multiple instances with the same name (say, Subway) will be returned. I want to limit the result to 10.

In English: Given me ten records (the entire record, not just certain columns) where every title is unique amongst the ten returned.

Upvotes: 1

Views: 760

Answers (2)

Greg Funtusov
Greg Funtusov

Reputation: 1447

You can simply use .first, i.e.

Venue.where(name: "Subway").first

If you need more than one element, pass a parameter to first:

Venue.where(name: "Subway").first(10)

To select one entry per distinct value in some column, you can use .group("column_name"):

Venue.where(some_condition).group("name")

Upvotes: 0

varatis
varatis

Reputation: 14750

ModelName.where(title: "Building")

If you provide a more specific question, I'll provide a more specific answer...

Upvotes: 0

Related Questions