【问题标题】:Rails scope/class method selecting virtual attributeRails范围/类方法选择虚拟属性
【发布时间】:2014-06-18 13:29:47
【问题描述】:

我目前正在将 has_scope gem 与模型上的范围/类方法结合使用,以过滤返回到我的 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 的结果,因为它的类型是Array,而不是ActiveRecord::Relation,因此我的wherehackery。对于上下文,我不能/不想返回数组的原因是结果集被传递给kaminari 进行分页。

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

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

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

提前致谢。

【问题讨论】:

    标签: ruby-on-rails activerecord kaminari scopes


    【解决方案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
    

    【讨论】:

    • 公平。在某个阶段,我认为我们会将status 移动到数据库中,因此它不会在运行时计算。但这是一个很好的临时答案——干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多