【问题标题】:One to Many Active Records Ruby on Rails一对多活动记录 Ruby on Rails
【发布时间】:2022-02-21 16:57:38
【问题描述】:

我正在开发基于 ruby​​ on rails 的数据捕获系统。我被困在一个点上,已经花了几个小时。我有一对多的关系,我需要根据状态过滤器获取数据。 我有两张桌子:

  1. 堆栈 2) 裁决 一个堆栈可以有多个裁决。现在的情况是我必须根据状态过滤来自 db 的数据。 如果我选择“is_pending”状态,我需要获取所有在裁决表中没有行的数据,如果在裁决表中有一行,则只获取“is_ready”和“is_final”列为假的那些行。

我的控制者:

def index
      @pagy, @stacks  = pagy(@study.stacks.filter_by_status(filtering_params(params)))
end

# A list of the param names that can be used for filtering the stack list
def filtering_params(params)
     params[:status]
end

我的模特:

 #scope
  scope :filter_by_status, -> (status) {
      if status.present?
        if status == "is_final"
          joins(:adjudication).where("adjudications.is_final": true)
        elsif status == "is_ready_to_adjudicate"
          joins(:adjudication).where("adjudications.ready_for_adjudication": true, "adjudications.is_final": false)
        elsif status == "is_pending_grading"
         **????????????????? Stuck Here ?????????????????**
        end
      end
  }

如果有人能指导我完成此操作,我将不胜感激。

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord scopes


    【解决方案1】:

    经过几个小时的搜索,我发现左连接在这种情况下很有帮助,另外我们需要对 ID 使用“is NULL”检查,因为它会给我们空记录,而 where 条件将返回匹配的行。

     #scope
      scope :filter_by_status, -> (status) {
          if status.present?
            if status == "is_final"
              joins(:adjudication).where("adjudications.is_final": true)
            elsif status == "is_ready_to_adjudicate"
              joins(:adjudication).where("adjudications.ready_for_adjudication": true, "adjudications.is_final": false)
            elsif status == "is_pending_grading"
              includes(:adjudication).where("adjudications.ready_for_adjudication": false, "adjudications.is_final": false)
              .or(includes(:adjudication).where("adjudications.stack_id": nil))
            end
          end
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多