Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build scope to order title

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 
like image 719
BV45 Avatar asked Apr 17 '15 13:04

BV45


2 Answers

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.

like image 138
Sharvy Ahmed Avatar answered Nov 11 '22 12:11

Sharvy Ahmed


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) }
like image 14
BroiSatse Avatar answered Nov 11 '22 14:11

BroiSatse