我正在使用 Ruby on Rails 3.2.2 和 MySQL。我想“合并”多个ActiveRecord::Associations
和一个或多个范围方法的结果。也就是说,我有:
class User < ActiveRecord::Base
has_many :a_user_relationships, :foreign_key => 'a_key'
has_many :b_user_relationships, :foreign_key => 'b_key'
has_many :a_articles, :through => :a_user_article_associations # Returns objects kind of 'Article'
has_many :b_articles, :through => :b_user_article_associations # Returns objects kind of 'Article'
end
class Article < ActiveRecord::Base
# Note: This is a scope method.
def self.public
where(:status => 'public')
end
end
鉴于上面的代码,我想运行一些方法(如下所示),以便通过执行尽可能少的数据库查询来检索所有公共“a”和“b”用户文章:
@user.all_articles
class User < ActiveRecord::Base
# Note: Code in the following method is incorrect, but maybe it helps
# understanding what I mean.
def all_articles
self.(a_articles & b_articles).public
(self.a_articles.public & self.b_articles.public)
end
end
可能吗?