Misha Moroshko
Misha Moroshko

Reputation: 171341

Rails 3: "redirect_to" doesn't work well after Ajax call

In my Rails 3 application user adds a new message to forum using Ajax:

<%= form_tag("/forum/add_new_message", :remote => true) do %>
  <%= text_area_tag("new_message_area") %>
<% end %>

Here is my controller's code:

def index
  @messages = Message.all
end

def add_new_message
  Message.create(:text => params[:new_message_area], ...)                 
  redirect_to(:action => 'index')
end

The problem is that after user adds a new message, redirect_to(:action => 'index') executed, but the page is not refreshed, i.e. I don't see the new message.

Why ?

Upvotes: 1

Views: 5434

Answers (2)

Mike
Mike

Reputation: 9842

I'd be tempted to go for something like this in the controller:

def index
  @messages = Message.all
end

def add_new_message
  Message.create(:text => params[:new_message_area], ...)                 
  render js: %(window.location.pathname='#{messages_path}')
end

Upvotes: 2

SuperMaximo93
SuperMaximo93

Reputation: 2056

The web browser is expecting some javascript to be executed after the ajax has been called. Your code should work when javascript is disabled in the browser.

In the add_new_message method you should add:

respond_to do |format|
  format.html { redirect_to(:action => 'index') }
  format.js
end

Then some javascript in add_new_message.js.erb will be executed, so to redirect to the index, the code in add_new_message.js.erb should look like:

window.location = '<%= forums_path %>'; //or whatever other path

Although both the HTML and javascript do the same thing. Why is the ajax needed in the first place?

Upvotes: 5

Related Questions