Rails 4 default scope

Ruby on-Rails-4Default Scope

Ruby on-Rails-4 Problem Overview


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

Ruby on-Rails-4 Solutions


Solution 1 - Ruby on-Rails-4

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

Solution 2 - Ruby on-Rails-4

This is what worked for me:

default_scope  { order(:created_at => :desc) }

Solution 3 - Ruby on-Rails-4

This also worked for me:

default_scope { order('created_at DESC') }

Solution 4 - Ruby on-Rails-4

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") }

Solution 5 - Ruby on-Rails-4

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) }

Solution 6 - Ruby on-Rails-4

This works for me in Rails 4

default_scope { order(external_updated_at: :desc) }

Solution 7 - Ruby on-Rails-4

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

Don't forget the -> symbol

Solution 8 - Ruby on-Rails-4

default_scope { 
      where(published: true) 
}

Try This.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe GattView Question on Stackoverflow
Solution 1 - Ruby on-Rails-4LukeView Answer on Stackoverflow
Solution 2 - Ruby on-Rails-4qubitView Answer on Stackoverflow
Solution 3 - Ruby on-Rails-4Alex HawkinsView Answer on Stackoverflow
Solution 4 - Ruby on-Rails-4FastSolutionsView Answer on Stackoverflow
Solution 5 - Ruby on-Rails-4Chris McKnightView Answer on Stackoverflow
Solution 6 - Ruby on-Rails-4HovoView Answer on Stackoverflow
Solution 7 - Ruby on-Rails-4AbelView Answer on Stackoverflow
Solution 8 - Ruby on-Rails-4aliAsadi92View Answer on Stackoverflow