1

我目前正在将has_scopegem 与模型上的范围/类方法结合使用,以过滤返回到我的 UI 的结果集。

我有一个模型Task,我希望能够过滤它status——模型上的一个虚拟属性。

Task模型有一些您可能需要了解的属性

uuid: Generated by SecureRandom
running: A boolean
success: A boolean
started_at: DateTime

计算status如下:

def status
    if running?
        'Running'
    elsif started_at.nil?
        'Queued'
    elsif success?
        'Finished'
    else
        'Failed'
    end
end

忽略这可能不是一种理想的方法这一事实,我目前已经实现了status过滤方法,如下所示:

def self.by_status(status)
  records = all.select {|s| s.status == status}
  where(uuid: records.map(&:uuid))
end

我不能只返回结果,select因为它是 typeArray而不是 an ActiveRecord::Relation,因此我的wherehackery。对于上下文,我不能/不想返回数组的原因是将结果集传递给kaminari分页。

请注意:我目前使用的方法符合我的要求,但我不喜欢它的完成方式。我觉得应该有更好的方法。

谁能建议一个更好的by_status方法来返回一个ActiveRecord::Relation吗?

tl;dr:需要一个类方法来返回一个ActiveRecord::Relation对虚拟属性的过滤。

提前致谢。

4

1 回答 1

1

这是我会怎么做

def self.by_status(status)
  case status
  when 'Running'  then where(running: true)
  when 'Finished' then where(success: true)
  when 'Queued'   then where(started_at: nil)
  else scoped #change this to all in Rails 4 since Model.all returns an AR Relation
  end
end
于 2014-05-01T23:46:10.243 回答