Rails-即使在我的服务器上显示“已重定向到http:// localhost:3000”,也无法重定向

问题描述

我有一个form_with可以在我的服务器上使用,但不能在我的兄弟中使用:

我认为自己的表单:

<%= form_with url: sessions_path,method: "post" do |f|%> 
          <h3 class="text-center text-info">Se Connecter</h3>
          <div class="form-group">
              <%= label_tag "email","Adresse mail:",class: "text-info" %><br>
              <%= f.email_field "email",class: "form-control" %>
          </div>
          <div class="form-group">
              <%= label_tag "password","Mot De Passe",class: "text-info" %><br>
              <%= f.password_field "password",class: "form-control" %>
          </div>
          <div class="form-group" style="padding: 20px;">
            <%= f.submit "Se connecter",class: "btn btn-info btn-md" %>
          </div>
      <% end %>

我的控制器:

def create
  user = User.find_by(email: params[:email])

  if user && user.authenticate(params[:password])
    session[:user_id] = user.id
    redirect_to gossips_path,:notice => "Bienvenue <%= User.find_by(id: session[:user_id]).first_name %>"
  else
    flash.Now[:danger] = 'Email ou Mot De Passe invalide'
    render 'new'
  end
end

我的服务器:

Started POST "/sessions" for ::1 at 2020-10-04 13:10:25 +0200
Processing by SessionsController#create as JS
  Parameters: {...}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email","..."],["LIMIT",1]]
  ↳ app/controllers/sessions_controller.rb:8
#<User:0x00007f667d7f36f0>
Redirected to http://localhost:3000/gossips
Completed 302 Found in 246ms (ActiveRecord: 0.2ms)


Started GET "/gossips" for ::1 at 2020-10-04 13:10:26 +0200
Processing by GossipsController#index as JS
  Rendering gossips/index.html.erb within layouts/application
  Gossip Load (0.4ms)  SELECT "gossips".* FROM "gossips"
  ↳...
  Rendered gossips/index.html.erb within layouts/application (75.5ms)
Completed 200 OK in 102ms (Views: 85.6ms | ActiveRecord: 12.8ms)

但是我的浏览器停留在同一页面上。我不知道为什么 你能帮我吗?

解决方法

<%= form_with url: sessions_path,method: "post",local: true do |f|%>
  # ...
<% end %>

form_withform_for不同,默认为remote: true。这意味着该表单将默认发送AJAX请求,因此重定向在浏览器中不执行任何操作。您可以通过以下方式查看其AJAX请求:

Processing by SessionsController#create as JS