【问题标题】:Find all records with two conditions where one condition are true and other false查找具有两个条件的所有记录,其中一个条件为真,另一个条件为假
【发布时间】:2016-05-08 12:26:54
【问题描述】:

我正在尝试查找满足两个条件的所有关联记录。 我正在尝试这个,但它不起作用,示例:

  @students = @group.students
    .includes(:attendances)
    .where.not(attendances: {student_id: @ids, event_time_id: @event_id})

  @students = @group.students
    .includes(:attendances)
    .where.not(attendances: {event_time_id: @event_id})
    .where.not(attendances: {student_id: @ids})

  @students = @group.students
    .includes(:attendances)
    .where("attendances.student_id IN (?) AND NOT attendances.event_time_id = ?", @ids, @event_id)

我想获取组中存在的所有学生记录,并且没有使用@event_id 出勤或根本没有出勤。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 associations


    【解决方案1】:

    我认为这可能会做你想要的(未经测试),而不是看起来最优雅的代码......

    exists_fragment = "SELECT 1 FROM attendances WHERE student_id = students.id"
    
    @group.students
      .joins(:attendance)
      .where("attendances.event_id <> ? OR NOT EXISTS(?)", @event_id, exists_fragment)
    

    【讨论】:

      【解决方案2】:

      工作解决方案:

        @students = @group.students.includes(:attendances)
          .where("attendances.event_time_id != ?", @event_id)
          .references(:attendances)
      
        @students_on = @group.students.includes(:attendances)
          .where(attendances: { event_time_id: @event_id })
      
        @students = @students - @students_on
      

      不确定这是否是最佳解决方案,但它解决了上述问题

      更新 更少的代码版本:

        @students = @group.students
        @students_exist =  @group.students.includes(:attendances)
          .where(attendances: { event_time_id: @event_id })
        @students = @students - @students_exist
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-05
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 2017-07-05
        • 2017-06-08
        • 1970-01-01
        相关资源
        最近更新 更多