Skip to content
This repository has been archived by the owner on Mar 30, 2022. It is now read-only.

Common issues

ernie edited this page Apr 11, 2012 · 5 revisions

Common issues

This is a collection of issues arising from misconceptions about Squeel that frequently crop up on the issue tracker.

Scopes

Like any other scopes, scopes that use the Squeel DSL must be wrapped in lambdas if you want them to be lazy evaluated. For instance:

# DO NOT USE!
scope :recent, where{created_at > 1.week.ago}

Won't work -- for long. The value of 1.week.ago will be interpreted when the model is loaded, and never again. Instead, use a lambda:

scope :recent, lambda { where{created_at > 1.week.ago} }

or a class method:

def self.recent
  where{created_at > 1.week.ago}
end

DSL is instance_evaled

The Squeel DSL operates inside an instance_eval. This means that you won't have access to instance methods or instance variables from the calling class. You will, however, have access to local variables that exist inside the closure from which you call it.

So, if you intend to use, for instance, params[:id] inside a Squeel block, you can do it in one of two ways. First, you can assign the variable locally:

params_id = params[:id]
@article = Article.where{id == params_id}.first

Alternately, you can use the my keyword, which grants you access to the instance from which the DSL was called:

@article = Article.where{id == my{params[:id]}}.first
Clone this wiki locally