Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DISTINCT with ActiveRecord

I'm using ActiveRecord / RoR.

My table looks like this:

id (int), start_time(time), end_time(time), ...

1, 20:00, 23:00

2, 20:00, 23:00

3, 16:00, 20:00

4, 16:00, 23:00

5, 20:00, 22:00

6, 16:00, 20:00

I need to return the records that have a combination distinct start_time + end_time combination.

like image 425
recursive_acronym Avatar asked Apr 09 '11 15:04

recursive_acronym


People also ask

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is an ActiveRecord relation object?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What is select distinct in SQL?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Is ActiveRecord a framework?

1.3 Active Record as an ORM Framework Represent inheritance hierarchies through related models. Validate models before they get persisted to the database. Perform database operations in an object-oriented fashion.


1 Answers

YourModelClass.select("DISTINCT start_time, end_time")

This will return objects that aren't strictly records but they will inherit from ActiveRecord::Base and you can do pretty much anything with those objects that doesn't write to the database.

http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

like image 148
MDaubs Avatar answered Sep 19 '22 01:09

MDaubs