0

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:

  • Take the percentage of the latest job (a job with max id), which percentage isn't nil.
  • If there are no jobs, or all jobs percentage is nil, it should be 23.

What is the easiest method to calculate this ?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.