I am trying to create a scope that will order by the title(:title)
. The title column resides in the Post Model. I read through the scopes section on the Active Record querying section and the one on StackOverFlow but it is not quite clear. Can someone point me in the right direction possibly?
I have 4 models:
Comment
Post
User
Advertisement
class Post < ActiveRecord::Base
attr_accessible :body, :title, :user
has_many :comments
belongs_to :user
default_scope {order('created_at DESC')}
scope :ordered_by_title {order('title' )} #What I initially built
end
When you do not have any default_scope
with order
:
scope :ordered_by_title, -> { order(title: :asc) }
When you have a default_scope
with order
then you need to use reorder
:
default_scope { order(created_at: :desc) }
scope :ordered_by_title, -> { reorder(title: :asc) }
or order
with unscope
:
default_scope { order(created_at: :desc) }
scope :ordered_by_title, -> { order(title: :asc).unscope(:order) }
The reorder
method overrides the default scope order.
Unfortunately simple order
will not work. Active Record allows you to specify multiple orders on a single association (which will order firstly by created_at
column and then by title
- second ordering will not change anything in this case). You need to tell rails that you want to ignore previous order statement using reorder
method.
scope :ordered_by_title, -> { reorder(title: :asc) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With