SsPay
SsPay

Reputation: 199

Why redirect doesn't work during submit form?

I have form on page.

    <%= form_with(url: join_battles_path, method: "get") do %>
      <%= collection_select(:team_id, :team_id, Team.all, :id, :name) %>
      <%= hidden_field_tag 'battle_id', battle.id %>
      <%= submit_tag "Join", class: 'btn btn-primary btn-sm' %>
    <% end %>

And method in controller :

  def join
    @battle = Battle.find(params[:battle_id])
    @battle.teams << Team.find(params[:team_id])
    redirect_to root_path
  end

But during submit form, results are saving, but on page nothing happens (redirect doesn't work)

Upvotes: 0

Views: 113

Answers (1)

arieljuod
arieljuod

Reputation: 15838

When you use the form_with helper, Rails, by default, uses a remote form (an ajax request), so it responds with a .js view and you can't use redirect like that for ajax requests.

You have 3 options:

  • add the option local: true to the form_with helper
  • use a different helper like form_for or form_tag that does http request by default instead of ajax
  • respond with a js view with a code like window.location.replace('<%= root_path %>')

Upvotes: 2

Related Questions