Created
November 12, 2012 23:59
-
-
Save ilake/4062922 to your computer and use it in GitHub Desktop.
The 10 Most Underused ActiveRecord::Relation Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # http://blog.mitchcrowe.com/blog/2012/04/14/10-most-underused-activerecord-relation-methods/ | |
| 1. Merge | |
| class Account < ActiveRecord::Base | |
| # ... | |
| # Returns all the accounts that have unread messages. | |
| def self.with_unread_messages | |
| joins(:messages).merge( Message.unread ) | |
| end | |
| end | |
| 3. scoping | |
| Comment.where(:post_id => 1).scoping do | |
| Comment.first # SELECT * FROM comments WHERE post_id = 1 | |
| end | |
| 6. find_each | |
| Book.where(:published => true).find_each do |book| | |
| puts "Do something with #{book.title} here!" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment