1772298f2d14152c13bbd3221e6ab6ec

Hi,
A partner and I were trying to figure how to do the code below in a named scope, but failed each time. We were wondering if anyone here would be able to get an equivalent result, but in a much shorter, efficient manner. The current way would require use to grab all of the records in issues, so we're trying to figure out a way to offload that work to MySQL. Any ideas?

def self.status_name(status)
    holder = []
    Issue.all.each do |record|
      if record.logs.first(:order => "created_at DESC").status.name == status
         holder << record
      end
    end
    holder
  end

Refactorings

No refactoring yet !

A8d3f35baafdaea851914b17dae9e1fc

Adam

July 15, 2010, July 15, 2010 05:33, permalink

No rating. Login to rate!

I attempted to infer your model structure based on what you have given. Assuming I am correct:

class Issue < ActiveRecord::Base
  has_many :logs
  
  scope :statuses, joins(:logs => :status).order('logs.created_at')
  scope :status_name, lambda { |name|
    statuses.where('statuses.name' => name)
  }
end
Issue.status_name('A name')
1b6e26633e1ebea63c21f126c3da08e0

cna training

July 21, 2010, July 21, 2010 06:18, permalink

No rating. Login to rate!

Great information! I’ve been looking for something like this for a while now. Thanks!

Your refactoring





Format Copy from initial code

or Cancel