问题
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
?
回答1:
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
- it's shorter / clearer / more idiomatic, and
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'
来源:https://stackoverflow.com/questions/50490009/rails-activerecord-where-vs-merge