Sort in Ascending Order Rails

后端 未结 5 1605
我寻月下人不归
我寻月下人不归 2021-02-02 08:46

Hi I have this model

Model item

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


        
相关标签:
5条回答
  • 2021-02-02 09:17

    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)
    
    0 讨论(0)
  • 2021-02-02 09:18

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

    Item.order(:name)
    

    by default this sorts ascending.

    0 讨论(0)
  • 2021-02-02 09:24

    In your query, you can use/add ORDER BY itemType ASC

    0 讨论(0)
  • 2021-02-02 09:30

    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.

    0 讨论(0)
  • 2021-02-02 09:32

    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

    0 讨论(0)
提交回复
热议问题