Pan
Pan

Reputation: 1

Rails 3 ActiveRecord Sort on Computed Attribute

What I have is a named scope that is called in a Class method. An additional sort is done on the Array. What I want to do is do the named_scope and sort in a single step. The attribute that I am sorting on is not a column in the database it is a computed value. What I need is the oldest transaction in a "Created" status.

scope :transactions_in_created_status,
      where('trnsts in (?) and regsam = ?', 'Created', TYPE)

def self.oldest_transaction_in_created_status
  result = Transaction.transactions_in_created_status.sort{|a,b|         [a.update_date,a.update_time] <=> [b.update_date, b.update_time]}           
  result[0] 
end

I tried exactly what is posted below, but I get the ODBC error "update_date" not found.
def update_date converts a mmddyy to ccyymmdd end

Upvotes: 0

Views: 572

Answers (2)

Pan
Pan

Reputation: 1

scope :transactions_in_created_status,
  where('trnsts in (?) and regsam = ?', 'CREATED', TYPE) do
    def oldest
      sort{|a,b|[a.update_date,a.update_time] <=> [b.update_date, b.update_time]}.first      
    end
  end 

Upvotes: 0

spullen
spullen

Reputation: 3317

scope :transactions_in_created_status,
      where('trnsts in (?) and regsam = ?', 'Created', TYPE).order('update_date DESC, update_time DESC')

Then to get 1 you can just call first:

Transaction.transactions_in_created_status.first

Upvotes: 1

Related Questions