Rails: ActiveRecord where vs merge

心不动则不痛 提交于 2019-12-23 06:58:13

问题


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

  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'


来源:https://stackoverflow.com/questions/50490009/rails-activerecord-where-vs-merge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!