Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 default scope

In my Rails app have a default scope that looks like this:

default_scope order: 'external_updated_at DESC' 

I have now upgraded to Rails 4 and, of course, I get the following deprecation warning "Calling #scope or #default_scope with a hash is deprecated. Please use a lambda containing a scope.". I have successfully converted my other scopes but I don't know what the syntax for default_scope should be. This doesn't work:

default_scope, -> { order: 'external_updated_at' } 
like image 234
Joe Gatt Avatar asked Aug 29 '13 08:08

Joe Gatt


People also ask

What are default scopes in Rails?

With default scopes, we can change/specify how records are retrieved by default from Active Record database. Any subsequent queries to the database will be retrieved/rendered following the default scope definition. For example, call the select Active Record finder method on the Tea class where rating is not exactly 3.

What are scopes in Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

Why do we use scope in Rails?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.


2 Answers

Should be only:

class Ticket < ActiveRecord::Base   default_scope -> { order(:external_updated_at) }  end 

default_scope accept a block, lambda is necessary for scope(), because there are 2 parameters, name and block:

class Shirt < ActiveRecord::Base   scope :red, -> { where(color: 'red') } end 
like image 85
Luke Avatar answered Sep 30 '22 18:09

Luke


This is what worked for me:

default_scope  { order(:created_at => :desc) } 
like image 20
qubit Avatar answered Sep 30 '22 17:09

qubit