sparkle
sparkle

Reputation: 7390

Rails Chained Or conditions in Where

I have to do this query (squeel) in Active Record. my{@my_lessons_ids} is an array with all IDS >> stands for "WHERE IN" | stands for "OR"

    my_courses = current_user.courses

@my_posts_ids   = current_user.enrollments.map{|e| e.academy.posts.map(&:id)}
@my_courses_ids = my_courses.map(&:id)
@my_groups_ids  = current_user.groups.map(&:id)
@my_lessons_ids = my_courses.map{|c| c.lessons.map(&:id)}

@my_wallposts = WallPost.where{
    ((wallable_type == "Lesson") && (wallable_id >> my{@my_lessons_ids})) |
    ((wallable_type == "Post") && (wallable_id >> my{@my_posts_ids})) |
    ((wallable_type == "Course") && (wallable_id >> my{@my_courses_ids})) |
    ((wallable_type == "Group") && (wallable_id >> my{@my_groups_ids})) 

}

@my_comments_ids = @my_wallposts.map{|w| w.comments.map(&:id)}
@my_wallposts_ids = @my_wallposts.map(&:id)

@activities = PublicActivity::Activity.where{
    ((trackable_type == "Lesson") & (trackable_id >> my{@my_lessons_ids})) | 
    ((trackable_type == "Post") & (trackable_id >> my{@my_posts_ids}))       |
    ((trackable_type == "Course") & (trackable_id >> my{@my_courses_ids}))   |
    ((trackable_type == "WallPost") & (trackable_id >> my{@my_wallposts_ids})) |
    ((trackable_type == "Comment") & (trackable_id >> my{@my_comments_ids})) 

}.order("id DESC")

I can't use "squeel" because it creates some conflicts with something else

Upvotes: 0

Views: 57

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You can use ARel

t = WallPost.arel_table

    WallPost.where(
      (t[:wallable_type].eq("Lesson"), t[:wallable_id].in(my{@my_lessons_ids})).or
      (t[:wallable_type].eq("Post"), t[:wallable_id].in(my{@my_posts_ids})) #and so on..

Upvotes: 1

Related Questions