2

ユーザーモデルには2つのスコープがあります。

scope :hard_deactivated, where(:hard_deactivated => true)
scope :soft_deactivated, where(:soft_deactivated => true)

ここまでは順調ですね

また

スコープ:deactivateを作成したいのですが、これには、hard_deactivateがtrueであるか、softdeactivateがtrueであるすべてのユーザーが含まれます。明らかに、私はこれを行うことができます:

scope :deactivated, where("hard_deactivated = ? or soft_deactivated = ?", true, true)

しかし、これはあまり乾燥しているとは感じません。

いいえ

また、逆スコープ:not_hard_deactivateを作成したいと思います。私はこれを行うことができます:

scope :not_hard_deactivated, where(:hard_deactivated => false)

しかし、繰り返しになりますが、特に私のスコープがより複雑になると、これは気分が悪くなります。not句の前のスコープによって生成されたSQLに何らかの方法またはワープがあるはずです。

4

3 に答える 3

3

アレルテーブルを使用します。

hard_deactivated_true = arel_table[:hard_deactivated].eq(true)
soft_deactivated_true = arel_table[:soft_deactivated].eq(true)

scope :deactivated, where(hard_deactivated_true.and(soft_deactivated_true))
scope :not_hard_deactivated, where(hard_deactivated_true.not)

参照:Rails3で名前付きスコープを反転することは可能ですか?

于 2013-01-11T15:09:16.783 に答える
1

「NOT」の部分については、次のようにすることができます。

extend ScopeUtils

positive_and_negative_scopes :deactivated do |value|
  where(:hard_deactivated => value)
end

そして、このメソッドを別のモジュールに実装します。

module ScopeUtils
  def positive_and_negative_scopes(name)
    [true, false].each do |filter_value|
      prefix = ("not_" if filter_value == false)
      scope :"#{prefix}#{name}", yield(filter_value)
    end
  end
end

「OR」の場合は、繰り返し発生するパターンによっては、似たようなものになる可能性があります。上記の簡単な例では、読みやすさを向上させないため、それだけの価値はありません。

scopes_with_adjectives_and_negatives :deactivated, [:soft, :hard]

module ScopeUtils
  def scopes_with_adjectives_and_negatives(name, kinds)
    kinds.each do |kind|
      positive_and_negative_scopes name do |filter_value|
        where("#{kind}_#{name}" => filter_value)
      end
    end
    scope :"#{name}", where(kinds.map{|kind| "#{kind}_#{name} = ?"}.join(" OR "), true, true)
    scope :"not_#{name}", where(kinds.map{|kind| "#{kind}_#{name} = ?"}.join(" AND "), false, false)
  end
end
于 2013-01-11T15:08:56.737 に答える
0

メソッドでSQLスニペットを使用するか(2番目の例のように)、 squeelwhereのような「砂糖」の宝石をもっと使用する必要があります

于 2013-01-11T15:08:01.793 に答える