Rails 4 default scope

54.1k views Asked by At

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' }
8

There are 8 answers

5
Luke On BEST ANSWER

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
0
Hovo On

This works for me in Rails 4

default_scope { order(external_updated_at: :desc) }
1
qubit On

This is what worked for me:

default_scope  { order(:created_at => :desc) }
0
Abel On
default_scope -> { order(created_at: :desc) }

Don't forget the -> symbol

0
FastSolutions On

This worked from me (just for illustration with a where) because I came to this topic via the same problem.

default_scope { where(form: "WorkExperience") }
0
Alex Hawkins On

This also worked for me:

default_scope { order('created_at DESC') }

0
Chris McKnight On

You can also use the lambda keyword. This is useful for multiline blocks.

default_scope lambda {
  order(external_updated_at: :desc)
}

which is equivalent to

default_scope -> { order(external_updated_at: :desc) }

and

default_scope { order(external_updated_at: :desc) }
0
aliAsadi92 On
default_scope { 
      where(published: true) 
}

Try This.