Skip to content

Instantly share code, notes, and snippets.

@ilake
Created November 12, 2012 23:59
Show Gist options
  • Select an option

  • Save ilake/4062922 to your computer and use it in GitHub Desktop.

Select an option

Save ilake/4062922 to your computer and use it in GitHub Desktop.
The 10 Most Underused ActiveRecord::Relation Methods
# 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