0

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

出来ますか?

4

1 に答える 1

0

2 つの個別の関連付けがあるため、少なくとも 2 つのクエリが必要です。

ここで常に両方の記事が必要な場合、これら 2 つの個別の記事に加えて、またはその代わりに、単純な「記事」の関連付けを行うことを妨げるものはありますか? そうすれば、 で記事を取得できますself.articles.public

于 2012-06-22T19:37:39.537 に答える