我偶然发现了一篇关于 Rails 3+ 范围的精彩文章:http ://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-以前-命名范围/index.html
您可以在此处(在“Crazy Town”部分中)阅读到可以合并来自不同模型的范围,如下所示:
class User < ActiveRecord::Base
scope :published, lambda {
joins(:posts).group("users.id") & Post.published
}
end
它可以按预期工作,并允许您执行以下操作:
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
我在我的 Rails 3.1 项目中尝试了这种方法,显然它不再起作用了。
所以我克隆了这篇文章的 Rails 3.0.0-beta1 项目,我亲眼看到这些人没有撒谎,事情正在按照他们所说的方式进行。
然后我 3.1'ed 了,现在我得到了:
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>'
==> 不再起作用了。
这让我很伤心,因为范围合并很棒,现在我不能像我想要的那样干。
你知道吗 :
- 两个版本之间发生了什么?
- 还有其他方法可以做到这一点吗?