2016-01-30 53 views
1

我試圖找到滿足兩個條件的所有關聯記錄。 我想這一點,但它不工作,例:查找所有記錄有兩個條件,其中一個條件是真的,其他假

@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或沒有出席所有的所有學生記錄。

回答

0

我想這可能會做你想要的(未經測試),而不是最優雅尋找代碼...

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) 
+0

我收到了一個mysql錯誤。 – GEkk

0

工作液:

@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 

不知道這是最好的解決辦法但它解決了上述問題

UPDATE 較少的代碼版本:

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