Reusing ActiveRecord scopes

You can use an ActiveRecord scope from one model to scope queries on another that joins it. This can be very convenient and keep your scopes DRY.

class Post < ActiveRecord::Base
  belongs_to :user
  scope :recent, lambda { order(:updated_at).last(10) }

class User < ActiveRecord::Base
  has_many :posts

It’s easy to get recent posts by saying User.posts.recent

But what if you want to fetch users who have recent posts?

users = User.joins(:posts).merge(Post.recent)

You can merge two scopes together and you end up with the conditions you would expect.


Note that you have to join :posts before you can merge a scope from Post.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s