Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort in Ascending Order Rails

Hi I have this model

Model item

class Inventory::Item < ActiveRecord::Base
  has_many :types, :class_name => "ItemType"
  attr_accessible :name
end

Model item_type

class Inventory::ItemType < ActiveRecord::Base
  belongs_to :item 
  attr_accessible :number
end

then let say in controller I want to sort types (which has class ItemType) in ascending order based on Item name. How do I do that?

For example,

  • ItemType number = 1 has Item name = Table
  • ItemType number = 2 has Item name = Chair
  • ItemType number = 3 has Item name = Window
  • ItemType number = 4 has Item name = Computer

So instead of sorting it from number, I want it sorted based on item.name(ASC) like this:

  • ItemType number = 2 has Item name = Chair
  • ItemType number = 4 has Item name = Computer
  • ItemType number = 1 has Item name = Table
  • ItemType number = 3 has Item name = Window
like image 257
muhihsan Avatar asked May 09 '13 07:05

muhihsan


4 Answers

Something like this should do the trick...

ItemType.includes( :item ).order( 'inventory_items.name DESC' )

Also, if you need to do this in many locations, you can accomplish the same thing by providing an :order parameter to your has_many call, instead - http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many.

like image 108
Brad Werth Avatar answered Nov 08 '22 03:11

Brad Werth


To retrieve records from the database in a specific order, you can use the order method:

Item.order(:name)

by default this sorts ascending.

like image 38
Andy Hayden Avatar answered Nov 08 '22 02:11

Andy Hayden


For making ASC (Default sorting mode) for name kind of fields (Alphabets),

You can use ORDER BY Clause in MySQL

Hence, In Rails you can simply use

Model.order(:field_name)
like image 2
Jyothu Avatar answered Nov 08 '22 02:11

Jyothu


You can also set default order in your Model like this:

default_scope order("#{self.table_name}.item_name ASC")

This will sort items by item_name without any change in controller

like image 1
Arif Avatar answered Nov 08 '22 01:11

Arif