Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to html from javascript request not working (Rails)

I'm sending a javascript request to a controller action to try to redirect to another html page if certain conditions aren't met. After looking through a few questions, this is what I've come up with:

def twittertweet
  if current_user && current_user.twitter_token
    ....
  else
    flash[:notice] = "You must be registered with Twitter to do that."
    respond_to do |format|
      format.js { render(:update) { |page| page.redirect_to authentications_url } }
    end
  end
end

I want to redirect_to the authentications_url. However, this is what happens:

Started POST "/twittertweet.json" for 127.0.0.1 at 2012-04-11 13:38:27 -0400
  Processing by ItemsController#twittertweet as */*
  Parameters: {"id"=>"22"}
  Category Load (0.3ms)  SELECT "categories".* FROM "categories" 
Rendered items/update.html.erb within layouts/application (0.0ms)
Completed 200 OK in 112ms (Views: 79.9ms | ActiveRecord: 5.7ms)

As you can see, it's just not even attempting to redirect_to the authentications_url. Yet I know the "else" statement is getting reached (I've put puts statements to help me find that out).

Any workarounds for this?

Update If you try DanS's solution, there's a MissingTemplateError. It's still trying to redirect to items#update:

ActionView::MissingTemplate (Missing template items/update, application/update with {:handlers=>[:erb, :builder, :coffee], :formats=>[:json], :locale=>[:en, :en]}. Searched in:
  * "/Users/dylandrop/Documents/givespend/app/views"
  * "/Users/dylandrop/.rvm/gems/ruby-1.9.2-p290/gems/devise-2.0.4/app/views"
):    
like image 912
varatis Avatar asked Apr 11 '12 17:04

varatis


1 Answers

I guess you call twittertweet via ajax. Then respond to it via the javasctipt code:

format.js { render :js => "window.location.href = '#{some_path}'" }
like image 113
jdoe Avatar answered Oct 12 '22 12:10

jdoe