繁体   English   中英

在 Rails 中从不同范围创建一个关系

[英]Create one relation from different scopes in Rails

我有一种方法可以获取 scope 并生成过滤页面的链接。 此链接看起来像报告数

def other_total_reports(subjects, action, due_in = nil, locale_clause = nil)
    scopes = []

    scopes << due_in if due_in

    count = scopes.inject(subjects) { |obj, method| obj.public_send(method) }.count
   
    link_to count, { controller: 'user_reports', action: action, filter: filter }, class: ("overdue" if due_in == (:overdue)), target: "_blank"
end

应该计算未处理的报告总数,但由于对不同关系(范围)的一些过滤器,总数不太准确,所以当我通过主题时

UserReports.unprocessed

它效果不佳。 为了获得正确的数字,我必须结合已经计算过的特定范围并作为主题传递

UserReports.unprocessed.videos, UserReports.unprocessed.public_chats, UserReports.unprocessed.answers_only, UserBlockLog.unprocessed.photos, UserReports.unprocessed.questions_only.questions_reasons, UserReports.unprocessed.profiles.profiles_reasons

后来这个 scope 必须使用,所以它应该是一个 ActiveRecord::Relation 排除 arrays 方法。 谢谢你们的帮助!

以这种方式找到解决方案:

    total = UserReports.unprocessed.videos, 
            UserReports.unprocessed.public_chats, 
            UserReports.unprocessed.answers_only, 
            UserReports.unprocessed.photos, 
            UserReports.unprocessed.questions_only.questions_reasons, 
            UserReports.unprocessed.profiles.profiles_reasons

    @reports_total = UserReports.where(id: total.map(&:id))

如果您的范围只有“where”子句,您可以使用“或”将您的范围仅加入一条记录

scopes.each_with_object(subjects).inject(nil) do |memo, (scope, original_record)|
  # Applies the scope to your record
  result = obj.public_send(scope)
  # You can`t apply your "or" if you don't have any of your scopes applied already
  # So we skip the first iteraction
  next result unless memo

  memo.or(result)
end

如果您的范围确实有比“where”更多的子句,您可以使用ActiveRecord::QueryMethods#includes_values包含所有范围“包含”值以至少使用“包含”子句

如果其他子句太复杂而无法像 'select'、'from' 或 'group by' 那样连接,则它必须调整它们中的每一个以在每个 scope 中使用“联合”,即使那样,'例如,group by' 子句效果不佳,因此如果您的问题仍未解决,请在您的问题中说明您的范围有多复杂

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM