Roberto Pezzali
Roberto Pezzali

Reputation: 2494

How to handle additional param in controller

I'm learning Rails and I have now a good knowledge about controllers. By the way I always have some issues and I don't know whats the best way to solve them.

One of these is the search: I have a search in my website and I must reorder results for relevance and date.

My search controller

def show
    @query = params[:query]
    @contents  = Content.published.search_by_text(@query).page(params[:page]).per(12)
  end

This is the default search. I have to implement also the "data order" search and I think to do something like this:

 def show
    @query = params[:query]
    @contents  = Content.published.search_by_text(@query).page(params[:page]).per(12)
    if params[:order]
       @contents = Content.published.search_by_text(@query).reorder("created_at DESC").page(params[:page]).per(12)
    end
  end

Is there a better way to obtain my result?

Upvotes: 0

Views: 41

Answers (1)

Intrepidd
Intrepidd

Reputation: 20858

Fortunately, rails allows us to chain calls when using Active Record (Rails' ORM)

Here is a possibility :

def show
  @query = params[:query]
  @contents  = Content.published.search_by_text(@query)
  @contents = @contents.reorder("created_at DESC") if params[:order]
  @contents = @contents.page(params[:page]).per(12)
end

Upvotes: 2

Related Questions