Posted about 11 years ago. Visible to the public.

Safely chain scopes with hash conditions

There is a nasty bug in all version of Rails 2 and some versions of Rails 3.x where two chained scopes with hash conditions on the same attribute would overwrite each other.

This is a horrible security issue if you are using scopes to limit what a user may see or change Archive .


If you are using an affected Rails version and cannot switch to a fixed version, you can use this manual workaround.

Copy the attached initializer into your project. You can then use a new pseudo-scope chain_safely that guarantees that conditions in the current chain are not going to be overwritten by the next chain link.

Use this for cases where you use scopes to restrict access, and want to further filter this scope based on user input:

class ArticlesController < ApplicationController def index articles = visible_articles articles = articles.chain_safely.for_users(params[:user_id_filter]) if params[:user_id_filter] end private def visible_articles current_user.articles end end

Note that if you want to chain multiple scopes safely, you need to insert a chain_safely between each two links in the chain:


Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Henning Koch
Last edit:
almost 7 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more