How to add conditional where clauses in rails

前端 未结 2 1925
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 20:50

I am a rails newbie and am trying to perform a search on a table with rails, and i\'m just using my sql knowledge to do this. But this just doesn\'t seems like rails or ruby

2条回答
  •  萌比男神i
    2020-12-09 21:14

    You can apply multiple where calls to a query so you can build your base query:

    query = User.joins(...)
                .group(...)
                .select(...)
                .where('users.id = :user_id', :user_id => self.id)
    

    and then add another where call depending on your date interval:

    if(begin_date && end_date)
      query = query.where(:created_at => begin_date .. end_date)
      # or where('created_at between :begin_date and :end_date', :begin_date => begin_date, :end_date => end_date)
    elsif(begin_date)
      query = query.where('created_at >= :begin_date', :begin_date => begin_date)
    elsif(end_date)
      query = query.where('created_at <= :end_date', :end_date => end_date)
    end
    

    Each where call adds another piece to your overall WHERE clause using AND so something like:

    q = M.where(a).where(b).where(c)
    

    is the same as saying WHERE a AND b AND c.

提交回复
热议问题