2011-03-04 111 views
0

工作模型ID百分比场(等等)。可以是。的Rails 3 MySQL查询问题

我想设置一个默认百分比这里:

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

应该这样计算:

  • 就拿最近的作业的百分比(最高ID工作),其中百分比不是nil
  • 如果没有作业或所有作业百分比nil,它应该是23

什么是计算这个最简单的方法是什么?

回答

2

你或许应该这样做在你的Job型号:

[更新]

添加了对回调new_record?测试,因为百分比可以合法地nil;我们不希望覆盖它,如果它以前被设置为这样。

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 
1

您必须根据需要编写一个命名作用域以查找最近的记录。

 
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