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) }
end

class User < ActiveRecord::Base
  has_many :posts
end

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.

Nice!

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

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s