过滤 ActiveRecord::Relation 并根据条件选择重复项

时间:2021-02-15 16:19:36

标签: ruby-on-rails select activerecord filter group-by

我有一个基于多个条件过滤记录的类方法的工作解决方案。但在我看来它太复杂了......

  # Filter relevant records (for given person and on given date).
  def self.relevant(person, date)
    records = select { |r| !r.demographic || r.demographic.relevant?(person, date) }

    return records unless person.mother?

    records.group_by(&:component)
       # The group can only contain one or 2 records.
       # When there are 2, prioritize the one with the `demographic.maternity` association...
       .map do |m, g|
         [m, g.size == 1 ? g : [g.select { |r| r.demographic.maternity }]]
       end
  end

0 个答案:

没有答案