我目前正在将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
因为它是 typeArray
而不是 an ActiveRecord::Relation
,因此我的where
hackery。对于上下文,我不能/不想返回数组的原因是将结果集传递给kaminari
分页。
请注意:我目前使用的方法符合我的要求,但我不喜欢它的完成方式。我觉得应该有更好的方法。
谁能建议一个更好的by_status
方法来返回一个ActiveRecord::Relation
吗?
tl;dr:需要一个类方法来返回一个ActiveRecord::Relation
对虚拟属性的过滤。
提前致谢。