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 :
The &
method doesn't look like it works anymore (too bad, I found the syntax was neat). You can replace it with ActiveRecord::Relation#merge
:
class User < ActiveRecord::Base
scope :published, lambda {
joins(:posts).group("users.id").merge(Post.published)
}
end
Edit
And it looks like it won't be back, trying it in rails 3.0.10 gives a deprecation warning:
DEPRECATION WARNING: Using & to merge relations has been deprecated and will be removed in Rails 3.1. Please use the relation's merge method, instead.
Here's the commit deprecating it, in case someone's interested: https://github.com/rails/rails/commit/66003f596452aba927312c4218dfc8d408166d54
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With