Misha Moroshko
Misha Moroshko

Reputation: 171321

Rails 3 MySQL query question

My Job model has id and percentage fields (among others). percentage may be nil.

I would like to set a default percentage here:

class JobsController
  def new
    ...
    @job.percentage = <what should be here?>
    ...
  end
end

It should be calculated like this:

What is the easiest method to calculate this ?

Upvotes: 0

Views: 267

Answers (2)

Ashish
Ashish

Reputation: 5791

You have to write a named scope for finding recent record according to your need.

named_scope :recent, :conditions => "percentage != '' && 
             percentage IS NOT NULL", :order => 'ID DESC', :limit => 1

####Before Save

def calculate_default_percent
  record = Job.recent.first
  self.percentage ||= (record.nil? ? 23 : record.percentage)
end

Upvotes: 1

Michelle Tilley
Michelle Tilley

Reputation: 159095

You should probably do this in your Job model:

[Update]

Added a test for new_record? in the callback, since percentage can legitimately be nil; we don't want to override it if it's been previously set as such.

class Job < ActiveRecord::Base
  after_initialize :calculate_default_percent

  # other stuff

  private

    def calculate_default_percent
      if self.new_record?
        conditions = { :conditions => "percentage NOT NULL" }
        self.percentage = Job.last(conditions).nil? ? 23 : Job.last(conditions).percentage
      end
    end
end

Upvotes: 2

Related Questions