jacksonecac
jacksonecac

Reputation: 284

Rails query with distinct

I have having a tough time figuring out how to query my database correctly.

My query is like the following:

@events = Event.where("startdate > '#{now}'")

There is a column in the events model called name, I need to return all the events whose name is distinct, but I also need ALL the columns. How would I accomplish this?

I thought that this would work but it isn't:

@events = Event.where("startdate > '#{now}'").uniq

Then I realized that it has no idea what to look at to judge uniqueness, how do I tell unique to look at the name column to judge uniqueness?

Data:

ID | Name         | Description  | start
1    christmas      holiday        12-25-16
2    christmas      holiday        12-25-17  
3    thanksgiving   holiday        11-24-16

Should return

1    christmas      holiday        12-25-16
3    thanksgiving   holiday        11-24-16

thanks,

Upvotes: 1

Views: 1594

Answers (2)

Ursus
Ursus

Reputation: 30071

You can use a block to say to uniq how to do the work

@events = Event.where("startdate > '#{now}'").uniq(&:name)

Otherwise, and probably this is better, you could do all in SQL, because uniq is not, it iterates your resultset.

@events = Event.where("startdate > '#{now}'").group(:name)

Upvotes: 3

mboya berry
mboya berry

Reputation: 1

You can have the query run in the following manner:

@event = Event.where("startdate > '#{now}'").uniq(:name)

this will be able to give you data with only unique entries.

Upvotes: 0

Related Questions