7

I made a before_filter in some of my controller to redirect keyword searches to the parent controller

It's very simple:

  before_filter :redirect_search
  def redirect_search
    redirect_to controller: "buildings", action: "index", format: "html" if params[:q].present?
  end

Please note that the keyword_search is sent in "js" format

Everything seems to work. When I look at the server, I can see that the buildings/index is run and that the page is rendered but nothing happens in the browser.

In the browser's console I see this

GET http://localhost:3000/buildings.html 200 OK

It has the html page in the response body

This means that buildings/index is run as html but then sent as js to the browser.

Why is that so? How can I fix it?

2
  • can you try adding a return at the end of redirect_search ?
    – Raghu
    Sep 5, 2013 at 7:09
  • 2
    You mean you are using AJAX to go to keyword searches and there you are redirecting it to another url.html ?
    – techvineet
    Sep 5, 2013 at 7:20

3 Answers 3

18

Try with

def redirect_search
     respond_to do |format|
            format.html {redirect_to buildings_path} if params[:q].present?
            format.js {render :js => "window.location.href='"+buildings_path+"'"} if params[:q].present?
     end
end
13

Thanks to Bachan's answer, I could solve my issue this way:

  def redirect_search
    render :js => "window.location.href='"+buildings_path+"'" if params[:q].present?
  end

Thanks!

2
  • 20
    Wow is that ugly. Is there something missing here in Rails, or are we not doing things the Rails way to begin with?
    – ajbraus
    Dec 31, 2013 at 4:57
  • 1
    I actually needed that and this is the only way I could make it work, in 2021 with Rails 6. If anyone knows something better nowadays please comment!
    – Tashows
    Jan 16, 2021 at 16:44
2

I think the problem is in the view which is doing the request

you are sending a JS request (ajax), so you should return a js.erb file and render new HTML using js

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.