{"id":1181,"date":"2010-07-05T12:19:46","date_gmt":"2010-07-05T15:19:46","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=1181"},"modified":"2011-02-21T09:35:01","modified_gmt":"2011-02-21T12:35:01","slug":"new-active-record-scoping-syntax","status":"publish","type":"post","link":"https:\/\/blog.plataformatec.com.br\/2010\/07\/new-active-record-scoping-syntax\/","title":{"rendered":"New Active Record scoping syntax"},"content":{"rendered":"

You probably know that Active Record got a facelift<\/a> and is now powered by Active Relation. A new chainable-award-winning-lazy API was added and received great feedback! However, as more and more people are trying Rails 3 beta, a small incompatibility between the old and new syntax was found<\/a>. This post explains this incompatibility and how it was solved.<\/p>\n

The issue<\/h3>\n

Quoting the Lighthouse ticket, imagine the following scenario in Rails 2.3:<\/p>\n

\r\nclass Page < ActiveRecord::Base\r\n  default_scope :conditions => { :deleted_at => nil }\r\n\r\n  def self.deleted\r\n    with_exclusive_scope :find => { :conditions => \"pages.deleted_at IS NOT NULL\" } do\r\n      all\r\n    end\r\n  end\r\nend\r\n<\/pre>\n

If you rewrite it to the new 3.0 syntax, your first attempt would probably be:<\/p>\n

\r\nclass Page < ActiveRecord::Base\r\n  default_scope where(:deleted_at => nil)\r\n\r\n  def self.deleted\r\n    with_exclusive_scope :find => where('pages.deleted_at IS NOT NULL') do\r\n      all\r\n    end\r\n  end\r\nend\r\n<\/pre>\n

However, if you try it out on console, you will find out it does not work as expected:<\/p>\n

\r\nPage.all         #=> SELECT \"pages\".* FROM \"pages\" WHERE (\"pages\".\"deleted_at\" IS NULL)\r\nPage.deleted.all #=> SELECT \"pages\".* FROM \"pages\" WHERE (\"pages\".\"deleted_at\" IS NULL) AND (\"pages\".\"deleted_at\" IS NOT NULL)\r\n<\/pre>\n

To understand why it does not work, let’s take a look at the source code!<\/p>\n

Investigating the issue<\/h3>\n

With Active Relation, Active Record is no longer responsible to build queries. That said, ActiveRecord::Base<\/code> is not the one that implements where()<\/code> and friends, in fact, it simply delegates to an ActiveRecord::Relation<\/code> object. From ActiveRecord::Base source code<\/a>:<\/p>\n

\r\ndelegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped\r\n<\/pre>\n

And the scoped<\/code> implementation is shown below:<\/p>\n

\r\ndef scoped(options = nil)\r\n  if options.present?\r\n    scoped.apply_finder_options(options)\r\n  else\r\n    current_scoped_methods ? relation.merge(current_scoped_methods) : relation.clone\r\n  end\r\nend\r\n\r\ndef relation\r\n  @relation ||= ActiveRecord::Relation.new(self, arel_table)\r\n  finder_needs_type_condition? ? @relation.where(type_condition) : @relation\r\nend\r\n<\/pre>\n

As you can see, scoped<\/code> always returns an ActiveRecord::Relation that you build your query on top of (notice that ARel::Relation is not the same as ActiveRecord::Relation<\/a>).<\/p>\n

Besides, if there is any current_scoped_methods<\/code>, the scoped<\/code> method is responsible to merge this current scope into the raw relation. This is where things get interesting.<\/p>\n

When you create your model, current_scoped_methods<\/code> returns by default nil. However, when you define a default_scope<\/code>, the current scope now becomes the relation given to default_scope<\/code>, meaning that, every time you call scoped<\/code>, it returns the raw relation merged with your default scope.<\/p>\n

The whole idea of with_exclusive_scope<\/code> is to be able to make a query without taking the default scope into account, just the relation you give in as argument. That said, it basically sets the current_scope_methods<\/code> back to nil, so every time you call scoped<\/code> to build your queries, it will be built on top of the raw relation without the default scope.<\/p>\n

With that in mind, if we look again at the code which we were trying to port from Rails 2.3, we can finally understand what was happening:<\/p>\n

\r\ndef self.deleted\r\n  with_exclusive_scope :find => where('pages.deleted_at IS NOT NULL') do\r\n    self\r\n  end\r\nend\r\n<\/pre>\n

When we called where('pages.deleted_at IS NOT NULL')<\/code> above, we were doing the same as: scoped.where('pages.deleted_at IS NOT NULL')<\/code>. But, as scoped<\/code> was called outside<\/strong> the with_exclusive_scope<\/code> block, it means that the relation given as argument to :find<\/code> was built on top of default_scope<\/code> explaining the query we saw as results.<\/p>\n

For example, the following syntax would work as expected:<\/p>\n

\r\ndef self.deleted\r\n  with_exclusive_scope do\r\n    where('pages.deleted_at IS NOT NULL').all\r\n  end\r\nend\r\n<\/pre>\n

Since we are calling where<\/code> inside the block, the scoped<\/code> method no longer takes the default scope into account. However, moving the relation inside the block is not the same as specifying it to :find<\/code>, because if we were doing three queries inside the block, we would have to specify the same relation three times (or refactor the whole code to always do a query on top of this new relation).<\/p>\n

That said, it seems the previous with_exclusive_scope<\/code> syntax does not suit very well with ActiveRecord’s new API. Maybe is it time for change? Can we provide a better API? Which are the use cases?<\/p>\n

Identifying the use cases<\/h3>\n

The with_exclusive_scope<\/code> method has mainly two use cases. The first one, which we just discussed above, is to allow us to make a query without taking the default scope into account inside our models:<\/p>\n

\r\ndef self.deleted\r\n  with_exclusive_scope do\r\n    where('pages.deleted_at IS NOT NULL').all\r\n  end\r\nend\r\n<\/pre>\n

While this code looks ok, if we think about relations, we will realize that we don’t need to give a block to achieve the behavior we want. If the scoped<\/code> method returns a raw relation with the default scope, couldn’t we have a method that always returns the raw relation? Allowing us to build our query without taking the default scope into account?<\/p>\n

In fact, this method was already implemented in Active Record and it is called unscoped<\/code>. That said, the code above could simply be rewritten as:<\/p>\n

\r\ndef self.deleted\r\n  unscoped.where('pages.deleted_at IS NOT NULL').all\r\nend\r\n<\/pre>\n

Much simpler! So, it seems that we don’t need to support the block usage at all, confirm?<\/p>\n

Deny! Going back to the Page<\/code> example above, it seems we should never see deleted pages, that’s why we set the default_scope<\/code> to :deleted_at => nil<\/code>. However, if this application has an admin section, the admin may want to see all pages, including the deleted ones.<\/p>\n

That said, what we could do is to have one controller for the normal User and another for the Admin. In the former, we would always use Page.all<\/code>, and Page.unscoped.all<\/code> in the latter.<\/p>\n

However, if these controllers and views are very similar, you may not want do duplicate everything. Maybe it would be easier if we do something like this:<\/p>\n

def resource_class\r\n  if current_user.is_admin?\r\n    Page.unscoped\r\n  else\r\n    Page\r\n  end\r\nend<\/pre>\n

And, instead of always referencing the Page<\/code> class directly in our actions, we could call resource_class<\/code>. While this solution is also ok, there is a final alternative, that would require no changes to the current code. If you want to use the same controller for different roles, but changing the scope of what they are allowed to see, you could simply use an around_filter<\/code> to change the model scope during the execution of an action. Here is an example:<\/p>\n

\r\nclass PagesController < ApplicationController\r\n  around_filter :apply_scope\r\n\r\n  # some code ...\r\n\r\n  protected\r\n\r\n  def apply_scope\r\n    if current_user.admin?\r\n      Page.with_exclusive_scope { yield }\r\n    else\r\n      yield\r\n    end\r\n  end\r\nend<\/pre>\n

That said, being allowed to give a block to with_exclusive_scope<\/code> is actually useful and since we want to deprecate with_exclusive_scope<\/code> in favor of unscoped<\/code> in the future, we brought this very same syntax to unscoped<\/code> as well:<\/p>\n

def apply_scope\r\n  if current_user.admin?\r\n    Page.unscoped { yield }\r\n  else\r\n    yield\r\n  end\r\nend<\/pre>\n

Tidying it up<\/h3>\n

Well, after the behavior in with_exclusive_scope<\/code> was properly ported to the new API, we need to be sure we are not forgetting about anything... wait, actually we are.<\/p>\n

with_exclusive_scope<\/code> has an evil twin brother called with_scope<\/code> which behaves very similarly, except that it always build the query on top of the scoped<\/code> relation. It works like this:<\/p>\n

\r\nclass Page < ActiveRecord::Base\r\n  default_scope where(:deleted_at => nil)\r\nend\r\n\r\nPage.with_scope :find => { :conditions => { :active => true } } do\r\n  Page.all #=> Bring all active pages that were not deleted\r\nend\r\n<\/pre>\n

However, this feels way too hash-ish. Of course, we could use relations to make it a bit prettier:<\/p>\n

\r\nPage.with_scope :find => where(:active => true) do\r\n  Page.all #=> Bring all active pages that were not deleted\r\nend\r\n<\/pre>\n

This is ok, but it seems that we could improve it even more. That said, we added a new method to relations, called scoping<\/code>:<\/p>\n

\r\nPage.where(:active => true).scoping do\r\n  Page.all #=> Bring all active pages that were not deleted\r\nend\r\n<\/pre>\n

Yeah! Sign me up 'cause this looks way better than the previous syntax! And, if you check the original commit<\/a>, you will notice the unscoped<\/code> method with a block simply delegates scoping<\/code>:<\/p>\n

\r\ndef unscoped\r\n  block_given? ? relation.scoping { yield } : relation\r\nend\r\n<\/pre>\n

So, with unscoped<\/code> and scoping<\/code> implemented, we just need to commit, git push and be happy, confirm? Deny! There is one last case to check.<\/p>\n

create_with<\/h3>\n

If you payed attention properly, you can notice that every time we called with_exclusive_scope<\/code> and with_scope<\/code>, we always passed { :find => relation }<\/code> as hash, instead of simply giving the relation. This happens because these methods accept two hash keys: find and create.<\/p>\n

As you may expect, one specifies the behavior for create and the other for finding. In most of the cases, they are exactly the same and work with the new syntax:<\/p>\n

\r\npage = Page.where(:active => true).new\r\npage.active #=> true\r\n<\/pre>\n

However, for obvious reasons, this only works if the conditions are given as a hash. Consider this case:<\/p>\n

\r\npage = Page.where(\"active = true\").new\r\npage.active #=> nil\r\n<\/pre>\n

That said, there may be a few scenarios where you want to specify the creation conditions on its own, explaining the :find and :create options in with_exclusive_scope<\/code> and with_scope<\/code> methods. So, how can I achieve it with the new syntax? Easy!<\/p>\n

\r\npage = Page.create_with(:active => true).new\r\npage.active #=> true\r\n<\/pre>\n

If you provide both conditions as a hash and create_with<\/code>, create_with<\/code> always have higher priority:<\/p>\n

\r\npage = Page.where(:active => false).create_with(:active => true).new\r\npage.active #=> true\r\n<\/pre>\n

Note this syntax already existed, we are just making it explicit now as part of the new API! That said, commit, push and be happy!<\/p>\n

Wrapping up<\/h3>\n

All in all, with_exclusive_scope<\/code> and with_scope<\/code> are now part of the old ActiveRecord API giving place to the new, strong and vibrant unscoped<\/code> and scoping<\/code> methods!<\/p>\n

However, they are not going to be deprecated now. They will follow the same deprecation strategy as all the current methods<\/a>.<\/p>\n

And you? What do you think about this new scoping API?<\/p>\n","protected":false},"excerpt":{"rendered":"

You probably know that Active Record got a facelift and is now powered by Active Relation. A new chainable-award-winning-lazy API was added and received great feedback! However, as more and more people are trying Rails 3 beta, a small incompatibility between the old and new syntax was found. This post explains this incompatibility and how … \u00bb<\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0,"footnotes":""},"categories":[1],"tags":[106,107,115,108],"aioseo_notices":[],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/1181"}],"collection":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/comments?post=1181"}],"version-history":[{"count":17,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/1181\/revisions"}],"predecessor-version":[{"id":1884,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/posts\/1181\/revisions\/1884"}],"wp:attachment":[{"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/media?parent=1181"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/categories?post=1181"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.plataformatec.com.br\/wp-json\/wp\/v2\/tags?post=1181"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}