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
.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With