ActiveRecordの中身を勉強中

ActiveRecordの中身を勉強中

ActiveRecord::Baseの中身、SQLの処理対象を大まかに制限した上で具体的な条件を与えてWHERE句を決定する機構がScopeというパラメータで実装されているっぽく、そこを勉強中。

      # Scope parameters to method calls within the block.  Takes a hash of method_name => parameters hash.
      # method_name may be :find or :create. :find parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
      # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. :create parameters are an attributes hash.
      #
      #   Article.with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do
      #     Article.find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
      #     a = Article.create(1)
      #     a.blog_id # => 1
      #   end

→Scopeあり(with_scope)でブロックを呼び出す時に{メソッド名=>{パラメータのハッシュ}}を引数として渡すことで、そのScopeの範囲内でのみ.findの結果がヒットするように制限され、.createするとデフォルト値が制限できる。
と読める。
メソッド名が「:find」「:create」。ってmayって多分ってどういう意味だw将来的に増えるかも知れんけどごめんね的なニュアンスか…

      #
      # In nested scopings, all previous parameters are overwritten by inner rule
      # except :conditions in :find, that are merged as hash.
      #
      #   Article.with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do
      #     Article.with_scope(:find => { :limit => 10})
      #       Article.find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
      #     end
      #     Article.with_scope(:find => { :conditions => "author_id = 3" })
      #       Article.find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
      #     end
      #   end

→Scopeはネストすると内側の条件に上書きされてしまう?…そうか、その方がいいのか。いいのかしら…
まあ覚えておこう。

      #
      # You can ignore any previous scopings by using <tt>with_exclusive_scope</tt> method.
      #
      #   Article.with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do
      #     Article.with_exclusive_scope(:find => { :limit => 10 })
      #       Article.find(:all) # => SELECT * from articles LIMIT 10
      #     end
      #   end

→そしてwith_exclusive_scopeで強制的にチャラにした上でScopeしなおせる、と。