0

Rails 3.1 プロジェクトに、次のようなアクティブ レコード モデルがいくつかあるとします。

class Component < ActiveRecord::Base
    has_many :bugs
end

class Bug < ActiveRecord::Base
    belongs_to :component
    belongs_to :project

    scope :open, where(:open => true)
    scope :closed, where(:open => false)
end

class Project < ActiveRecord::Base
    has_many :bugs
    has_many :components_with_bugs, :through => :bugs, :conditions => ["bugs.open = ?", true]
end

components_with_bugs要するに、「スルー」モデルのスコープを設定したい has_many スルー アソシエーション ( ) があります。現在、スコープのコードを複製することでこれを行っています。

単一のデータベース クエリでコンポーネントをロードしながら、スルー モデルでスコープをcomponents_with_bugs再利用できるように、これを多数のスルー アソシエーション () で定義する方法はありますか? Bug.open(私はのようなものを想像しています:conditions => Bug.open

4

5 に答える 5

0

scopes とは別に、デフォルトのスコープを次のように記述します:
default_scope where(:open => true)「スルー」モデルでBug

class Bug < ActiveRecord::Base
  belongs_to :component
  belongs_to :project
  default_scope where(:open => true)
  scope :open, where(:open => true)
  scope :closed, where(:open => false)
end

Project モデルでは、:conditions => ["bugs.open = ?", true]を削除します。

class Project < ActiveRecord::Base
  has_many :bugs
  has_many :components_with_bugs, :through => :bugs
end

上記の方法でうまくいくと思います。

于 2012-12-04T05:25:58.913 に答える
0

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.htmlは指定します

:conditions関連付けられたオブジェクトが WHERE SQL フラグメントとして含まれるために満たさなければならない条件 (authorized = 1 など) を指定します。

したがって、次のように実行できます。

class Project < ActiveRecord::Base
  has_many :bugs
  has_many :components_with_bugs, :through => :bugs do
    def open
      where("bugs.open = ?", true)
    end
  end
end

編集:

別のモデルのスコープを条件として指定することはできません。あなたの場合、あなたがそれを実装した方法は正しいです。次のように別の方法で実装できます

has_many :components_with_bugs, :through => :bugs # in this case, no need to use the relation.

def open_bugs
  self.bugs.openn # openn is the scope in bug. Don't use name 'open'. It's a private method of Array.
end
于 2012-12-04T04:35:07.463 に答える
0

こんなの使えないの?

has_many :components_with_bugs, :through => :bugs, :conditions => Bug.open.where_values

私はそれをテストしていません。調査のためのパスを提案しているだけです

于 2012-12-21T09:10:14.533 に答える
0

以下を使用してみてください。

has_many :components_with_bugs, :through => :bugs do
   Bug.open
end

于 2012-12-04T07:14:11.903 に答える