Can you make an order in ruby โ€‹โ€‹after searching?

Is it possible to order a result set in ruby โ€‹โ€‹/ rails after performing a search? For example, is it possible to do something like this

Warning: not working

if type == 1
  @items = mycompany.items
else
  @items = myhome.items
end

@items = @items :order => "created_at"

I would suggest that something like this should be possible, but I'm still very new to RoR and can't find anything on google.

+3
source share
3 answers

I donโ€™t know why everything is all โ€œNo, you canโ€™tโ€, when itโ€™s possible in these areas.

For example, define as part of ActiveRecord :: Base:

named_scope :by_created_at, :order_by => 'created_at'

This allows you to transform a simple relation to an ordered one before it is actually restored:

@items = @items.by_created_at

: , , .

, :

reference =
  case (type)
  when 1
     mycompany
  else
    myhome
  end

@items = reference.items.all(:order_by => 'created_at')
+4

:

:

if type == 1
  @items = mycompany.items(:order => 'created_at')
else
  @items = myhome.items(:order => 'created_at')
end

:

@items.sort{|a,b| a.created_at <=> b.created_at}
+6

You can also use to a shortened version , available in the rails, as well as to simplify sorting your operator if you want to sort post-harvest facilities ActiveRecord: SymbolProcEnumerable#sort_by

@items.sort_by(&:created_at)
# is the same as @items.sort{ |a, b| a.created_at <=> b.created_at }
+5
source

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


All Articles