Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional where in Rails

How can I make a where optional in Rails?

I tried:

@pages = Page
             .where(status: params[:status].present? ? params[:status] : 1)
             .where(parent_id: nil) if params[:status].blank?
             .order(sort_column + ' ' + sort_direction)

But it looks to exit the block and instead returns: undefined method 'where' for true:TrueClass.

like image 741
Cameron Avatar asked Dec 15 '22 01:12

Cameron


2 Answers

You can split your declaration in three lines. Rails will lazy load your query, so don't worry about performance here. It will work fine:

@pages = Page.where(status: params[:status].present? ? params[:status] : 1)
@pages = @pages.where(parent_id: nil) if params[:status].blank?
@pages = @pages.order(sort_column + ' ' + sort_direction)
like image 197
lutchobandeira Avatar answered Dec 27 '22 02:12

lutchobandeira


You can pass the conditions to where in a hash syntax so just create a hash with all the conditions and pass it to where

conditions = {}
conditions[:status] = params[:status].present? ? params[:status] : 1
conditions[:parent_id] = nil if params[:status].blank?

@pages = Page.where(conditions).order(sort_column + ' ' + sort_direction)
like image 43
Deepak Mahakale Avatar answered Dec 27 '22 00:12

Deepak Mahakale