How to add conditional where clauses in rails How to add conditional where clauses in rails sql sql

How to add conditional where clauses in rails


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.


I cant think of a great reason why you would actually want to generate SQL in your code. Active record seems like a much more efficient solution for your needs, unless there is a reason why you cant use that.

Link explaining how to join tables with active record