I stumbled upon a wonderful article about scopes on Rails 3+ : http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html
You can read there (in 'Crazy Town' section) that it's possible to merge scopes from different models like this :
class User < ActiveRecord::Base
scope :published, lambda {
joins(:posts).group("users.id") & Post.published
}
end
which works just as expected, and allows you to do :
User.published.to_sql
#=> SELECT users.* FROM "users"
# INNER JOIN "posts" ON "posts"."author_id" = "users"."id"
# WHERE (posts.published_at IS NOT NULL AND posts.published_at <= '2010-02-27 02:55:45.063181')
# GROUP BY users.id
I tried this approach in my Rails 3.1 project and apparently it's not working anymore.
So I cloned the article's Rails 3.0.0-beta1 project, saw by my eyes that the guys are not lying and things are working the way they tell.
Then I 3.1'ed it up, and now I get :
ruby-1.9.2-p290 :003 > User.published.to_sql
User Load (0.3ms) SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."author_id" = "users"."id" GROUP BY users.id
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE (posts.published_at IS NOT NULL AND posts.published_at <= '2011-10-05 11:45:00.512231')
User Load (0.1ms) SELECT "users".* FROM "users"
NoMethodError: undefined method `to_sql' for []:Array
from (irb):3
from /home/jerefrer/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start'
from /home/jerefrer/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start'
from /home/jerefrer/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:9:in `require'
from script/rails:9:in `<main>'
==> Doesn't work anymore.
And that makes me sad, because scope merging was awesome and now I can't be as DRY as I want.
Do you know :
- What happened between the two versions ?
- Any other way to do the same ?