###ActiveRecordのwhereの仕組み
ActiveRecordのwhereの仕組みに関して教えてください。ActiveRecordのソースを読み込みpryで動作を止めてひとつひとつ確認しています。
User.where(id: 1)
を実行するとrails/activerecord/lib/active_record/querying.rbのdelegateでwhereがto: allになっています。
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :left_joins, :left_outer_joins, :or, :where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :distinct, :references, :none, :unscope, :merge, to: :all
したがってrails/activerecord/lib/active_record/scoping/named.rb
のallに処理が渡されています。
def all if current_scope current_scope.clone else default_scoped end end
ここのdefault_scopeの処理のあと
rails/activerecord/lib/active_record/relation/query_methods.rb
のwhereに処理が行きます。
def where(opts = :chain, *rest) if :chain == opts WhereChain.new(spawn) elsif opts.blank? self else spawn.where!(opts, *rest) end end
これはどのようにして実現しているのでしょうか?つまりどうやってdefault_scopeの処理の後にrelation/query_methods.rbのwhereへ行くようにしているのでしょうか?
最終的にはこちらの記事のThe Beauty of ActiveRecord::RelationにあるようにActiveRecord::Relationを使ったメソッドの数珠つなぎのような物を実装したいと考えております。
ただその前にActiveRecordのwhereが呼ばれた際にwhere->all->where(relation/query_methods)とつなげている仕組みを理解しなければ実現できそうにありません。
ソースのここを読めば分かるかも、といったヒントでも構いませんので教えていただけますでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/28 08:47
2017/04/28 09:39 編集