开发者

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:

  • 开发者_StackOverflowTake 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 ?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜