Answers to Optional where in Rails ( 2 )

  1. 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)
    
  2. 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)
    

Leave a reply to - Optional where in Rails

◀ Go back