0

AssistantTeacher クラスの新しい属性 mark_deleted を使用して、mark_deleted 属性が false である場合にのみ選択するという基本的な仮定で、すべてのクエリを機能させたいと考えています。

これは簡単です (標準の AR クエリ言語の代わりに squeel クエリ言語を使用)

class AssistantTeacher < ActiveRecord.Base
    # Gives a default query which always includes the condition here
    default_scope  {where{marked_deleted == false }}
end

つまり、AssistantTeacher.allのようなクエリは実際には

AssistantTeacher.all.where{marked_deleted == false}

よく働く。同様に、 AssistantTeacher.find_each() も制限付きで機能します。同じく

AssistantTeacher.where{atcode == "MPL"}

としても実行されます

I

ただし、注意が必要な部分: 特別な場合に、管理者などの default_scope を逆にする必要があります。

class AssistantTeacher < ActiveRecord.Base
  # Gives a default query which always includes the condition here
  default_scope  {where{marked_deleted == false }}
  # If a query is unscoped then the default_scope limitation does not apply
  # scoped is the default scope when there is no default_scope
  unscoped { scoped}
end

これはうまくいきます

def self.all_including_marked_deleted
    return unscoped{all} 
end

ただし、ブロックを使用してfind_eachの管理者バージョンのスコープ外を行う方法がわからないという質問

def self.find_each_including_marked_deleted &block
    return unscoped{find_each(block)} 
end

動作しません。私が考えることができる他のブロックとの組み合わせもありません。

私のオーバーライドメソッドfind_each_include_marked_deletedを取得して、そのブロックをスコープ外の呼び出しに渡すために私ができることは誰にでもありますか?

4

1 に答える 1

1

小さな構文の問題があります。&の前にa を追加するとblock、問題ないはずです。

def self.find_each_including_marked_deleted &block
    unscoped { find_each &block } 
end

何が起きてる?メソッド本体内では、block変数はのインスタンスですProc(これは、 param&の前で行っていることです)。blockをチェックすることでこれを確認できますblock.classfind_eachは proc ではなくブロックを取るため、&proc をブロックに戻すには が必要です。

泥のように透明?詳細については、こちらをご覧ください。

于 2013-08-12T02:51:33.077 に答える