【问题标题】:Rails where clause to select by specific attributeRails where 子句按特定属性选择
【发布时间】:2017-11-30 12:36:38
【问题描述】:

我有以下疑问:

我有以下型号:

2.1.5 :025 > OnlineCourseRegistration.last
 => #<OnlineCourseRegistration id: 14392, cart_id: 15177, user_id: 7133, course_class_id: 681, created_at: "2017-10-29 23:28:45", updated_at: "2017-10-30 20:18:53", exam_attempts: 0, exam_completed_at: nil, evaluation_completed_at: nil, status: "Active", score: "", add_extension: false, retest_cart_id: nil, retest_purchased_at: nil>

...我正在运行这个查询:

registrations = OnlineCourseRegistration.where(course_class_id: 123).where(status: "Completed").where("score >= ?", 80)

可能会返回多个相同 user_id 的记录。如果是这种情况,我只想返回最后一条记录...或该用户的最新 :exam_completed_at 日期的记录。

这里的上下文是整个循环:

registrations = OnlineCourseRegistration.where(course_class_id: 123).where(status: "Completed").where("score???? >= ?", 80)
          if !registrations.empty?
            registrations.each do |b|
              email_recipients << b
          end

我建立 email_recipients 数组,然后将其交给邮件程序。我遇到的问题是,如果用户被退回两次,那么他们会收到两封电子邮件。我只希望他们收到一封电子邮件,所以我想在返回的最后一条记录(或最近的exam_completed_at 日期的记录。

【问题讨论】:

  • 您可以在电子邮件数组上附加order(exam_completed_at: :desc).select('distinct on (email) name') 或直接调用.uniq...

标签: ruby-on-rails


【解决方案1】:

这是我想出的:

registrations = OnlineCourseRegistration.where(course_class_id: 842).where(status: "Completed").where("score? >= ?", 80).order(exam_completed_at: :desc)

注意我在上面添加了一个 order 子句,然后...

registrations = registrations.uniq_by {|u| u.user_id}

我不确定 uniq_by 是删除第一条记录还是最后一条记录,但这与附加的 order 子句相结合似乎可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多