rails3mysql查询问题
我的工作模型具有id和百分比字段(以及其他字段)。 百分比可能是rails3mysql查询问题,mysql,ruby-on-rails,ruby-on-rails-3,Mysql,Ruby On Rails,Ruby On Rails 3,我的工作模型具有id和百分比字段(以及其他字段)。 百分比可能是nil 我想在这里设置默认的百分比: class JobsController def new ... @job.percentage = <what should be here?> ... end end 类作业控制器 def新 ... @job.percentage= ... 结束 结束 应该这样计算: 取最新作业(id为maxid的作业)的百分比,其中percentage不是
nil
我想在这里设置默认的百分比:
class JobsController
def new
...
@job.percentage = <what should be here?>
...
end
end
类作业控制器
def新
...
@job.percentage=
...
结束
结束
应该这样计算:
- 取最新作业(id为maxid的作业)的百分比,其中percentage不是
nil
- 如果没有作业,或者所有作业的百分比为
,则应为23nil
最简单的计算方法是什么?您可能应该在您的
工作
模型中这样做:
[更新]
在回调中添加了对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
类作业“百分比不为空”}
self.percentage=Job.last(conditions).nil?23:作业。最后(条件)。百分比
结束
结束
结束
您可能应该在您的工作中这样做
型号:
[更新]
在回调中添加了对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
类作业“百分比不为空”}
self.percentage=Job.last(conditions).nil?23:作业。最后(条件)。百分比
结束
结束
结束
您必须根据需要编写一个用于查找最近记录的命名范围
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
命名范围:最近,:条件=>“百分比!=”&&
百分比不为空“,:order=>ID DESC',:limit=>1
####保存前
def计算默认百分比
记录=Job.recent.first
self.percentage | |=(record.nil±23:record.percentage)
结束
您必须根据需要编写一个命名范围来查找最近的记录 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 命名范围:最近,:条件=>“百分比!=”&& 百分比不为空“,:order=>ID DESC',:limit=>1 ####保存前 def计算默认百分比 记录=Job.recent.first self.percentage | |=(record.nil±23:record.percentage) 结束