如何根据条件简化Rails Active Record计算?

时间:2014-03-18 10:33:03

标签: ruby-on-rails activerecord ruby-on-rails-4 rails-activerecord

Job具有以下静态方法:

class Job < ActiveRecord::Base
  ...
  def self.super_job
    where('super_condition')
  end
  ...
end

有没有更优雅的方法来重写以下内容?

jobs = Job.where(...)

if some_condition
  jobs = jobs.sum('my_field')
else
  jobs = jobs.super_job.sum('my_field')
end

2 个答案:

答案 0 :(得分:0)

class Job < ActiveRecord::Base
  scope :super_jobs, -> {where('super_condition')}
end

jobs = jobs.super_jobs unless some_condition
jobs.sum("my_field")

答案 1 :(得分:0)

我经常为多个标准搜索执行类似的操作:

def index 
  @jobs = find_jobs
end

.....

private


def find_jobs
  jobs = Job.where(...) #Global search, here I defined pagination if needed
  #Then I stack my queries with conditions
  jobs = jobs = jobs.sum('my_field') if/unless condition
  jobs = jobs.super_job.sum('my_field') if unless
  ...
end

它几乎和你一样,但它对我来说足够清楚,我的代码更“整洁”。

来源:railcasts

编辑:正如Vimsha所说,范围也可以帮助清理代码。

希望它有所帮助!