Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Rails custom ordering of record

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.34k
    Comment on it

    Sometimes we need to display the records in a specific order. For that, we need some method
    Suppose I have the priorities ['0', '8', '4'] .And I have a model event with priority column.


    Now I need to get all the events order by priority. Here priorities are not following any order(DESC, ASC).


    So below code would work.
    Event.all(:order => "priority DESC")
    So we can do one thing, we can create a scope.
    then you will probably want to use a default_scope.

    For example:

    class Event < ActiveRecord::Base
    scope :by_priority, :order => order_by_case
    
    EVENT_ORDERED = ['0', '8', '4']
    
      def self.order_by_case
        ret = "CASE"
        EVENT_ORDERED.each_with_index do |p, i|
          ret << " WHEN reviewer_relationships = '#{p}' THEN #{i}"
        end
        ret << " END DESC"
      end
    
    end

    And then invoke the scope by something like this:

    @events=  Event.all.by_priority

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: