0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.