17

First, I am getting the review statuses between particular dates.

date_range = Date.parse(@from_date).beginning_of_day..Date.parse(@to_date).end_of_day

@review_statuses = ReviewStatus.where(updated_at: date_range)

Next, I need to apply an 'AND' condition.

    @review_cycle = params[:review_cycle]

    if @review_cycle.present?
      @review_statuses = @review_statuses.merge(
                           ReviewStatus.where(evidence_cycle: @review_cycle)
                                       .or(ReviewStatus.where(roc_cycle: @review_cycle)))
    end

Now for the below should I apply a 'where' or 'merge'.

@status = params[:status]

@review_statuses.where(evidence_status: :pass, roc_status: :pass) if @status == 'pass'

Can someone explain, when should we use merge instead of where?

strivedi183
  • 4,749
  • 2
  • 31
  • 38
Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61

1 Answers1

10

You generally want to use where except in special circumstances -- most commonly, to apply conditions to a secondary (joined) table in the query. This is becase

  1. it's shorter / clearer / more idiomatic, and
  2. merge has tricky edge cases: it mostly combines the two queries, but there are situations where one side's value will just override the other.

Given that, even your existing condition doesn't need merge:

# Unchanged
date_range = Date.parse(@from_date).beginning_of_day..Date.parse(@to_date).end_of_day
@review_statuses = ReviewStatus.where(updated_at: date_range)

# direct #where+#or over #merge
@review_cycle = params[:review_cycle]
if @review_cycle.present?
  @review_statuses = @review_statuses.where(evidence_cycle: @review_cycle).or(
                       @review_statuses.where(roc_cycle: @review_cycle))
end

# more #where
@status = params[:status]
@review_statuses = @review_statuses.where(evidence_status: :pass, roc_status: :pass) if @status == 'pass'
matthewd
  • 4,332
  • 15
  • 21
  • If `.or()` isn't working correctly that would be a matter for the Rails issue tracker, but I'm [quite confident](https://github.com/rails/rails/pull/16052) the above is accurate and will do what you want. – matthewd May 23 '18 at 16:17