How to create a header order area

Everything,

I am trying to create an area that will be sorted by title (: title). The header column is in the Post model. I read section one on StackOverFlow , but this is not entirely clear. Can someone point me in the right direction?

I have 4 models: Comment After 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 
+6
source share
2 answers

If you do not have default_scope with order :

 scope :ordered_by_title, -> { order(title: :asc) } 

When you have default_scope with order , 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 visibility order.

+28
source

Unfortunately, a simple order will not work. An active record allows you to specify several orders in one association (which will first order the created_at column, and then title - the second order will not change anything in this case). You need to specify the rails that you want to ignore the previous order instruction using the reorder method.

 scope :ordered_by_title, -> { reorder(title: :asc) } 
+9
source

Source: https://habr.com/ru/post/985352/


All Articles