ClosureCowboy
ClosureCowboy

Reputation: 21541

Staying DRY in Rails 3 with scopes and associations

Here are the relevant facts:

  1. Each topic has_many comments.

  2. The Comment model has a scope called very_popular, which we'll pretend involves comparing a several of its columns.

    def self.very_popular
      # lots of cool stuff
    end
    
  3. The Topic model has a scope called exciting, which includes all topics with very_popular comments.

Number 3 is where I'm stuck. The following results in a missing method exception, and as pitiful as it sounds, I don't know what else to try!

def self.exciting
  join(:comments).very_popular
end

How can I re-use the very_popular scope from the Comment model in the Topic model's scope?

Upvotes: 2

Views: 1329

Answers (1)

Alexei Danchenkov
Alexei Danchenkov

Reputation: 2082

You can't use the scope from another model directly. What you can do is merge the queries. Topic.joins(:comments).merge(Comment.very_popular)

Ryan explains it beautifully here: http://railscasts.com/episodes/215-advanced-queries-in-rails-3

Upvotes: 6

Related Questions