SHARE:
Uncategorized

ActiveRecord Conditional Queries

Flatiron School / 18 December 2012

The following is a guest post by Ericka Ward and originally appeared on her blog. Ericka is currently a student a The Flatiron School. You can learn more about her here, or follow her on twitter here.

ActiveRecord provides the where method to allow you to query your app’s database with specific conditions. The where method represents the WHERE part of a SQL statement. You can pass the method a string, array, or hash. It is important to note that this method will always return an object that is an ActiveRecord::Relation, which looks and behaves like an array.

I am currently working with some Flatiron School classmates on a rails app that aggregates blog posts, tweets and github activity for a group of people called Teamline. We use the where method in our app on several occassions.

In the example below, we are querying our posts table to find all the blog posts that belong to specific person.

The code above is equivalent to the following SQL statement:

The query returned an ActiveRecord::Relation object, which is essentially an array of all the blog posts with their attributes:

In another part of our code, we perform a query with multiple conditions. In this case, we wanted to find all the blog posts that belonged to a specific person and that was published between specific dates. We needed the method to be dynamic so rather than hard coding the values, we used variables that we define the larger custom method that this where method is a part of. In case you are not familiar with this syntax, person_id will replace the first question mark, start_date will replace the second and so on.

Again, this method will return an ActiveRecord::Relation object as well.

For more information on the many other ways you can use the where method to perform conditional queries, check out the documentation:
http://guides.rubyonrails.org/active_record_querying.html
http://api.rubyonrails.org/classes/ActiveRecord/Base.html

How to count Ruby Array items Previous Post How I Learned to Code in 8 Months Next Post