Question: Optional where in Rails

Question

Optional where in Rails

Answers 2
Added at 2017-01-03 16:01
Tags
Question

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.

Answers
nr: #1 dodano: 2017-01-03 16:01

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)
nr: #2 dodano: 2017-01-03 17:01

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)
Source Show
◀ Wstecz