Rails 4 default scope

こ雲淡風輕ζ 提交于 2019-11-27 17:47:03
Luke

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
qubit

This is what worked for me:

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

This also worked for me:

default_scope { order('created_at DESC') }

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

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

This works for me in Rails 4

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

Don't forget the -> symbol

aliAsadi92
default_scope { 
      where(published: true) 
}

Try This.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!