使用Rails和Hotwire提交表单时出错



我正在运行rails 6.1与热线。我正在创建一个登录表单采取电子邮件和密码,然后重定向到store_index路径。然而,我遇到了这个错误-错误:表单响应必须重定向到另一个位置。我尝试了以下方法但是得到相同的错误,

  1. 使用format.html { redirect_to store_index_path}

  2. 我注释掉了create函数中的所有内容,并添加了puts &; hello &;。然而,我还是得到了相同的错误。

我现在很困惑,有什么帮助吗

<%= form_with url: retailer_log_in_path, class: 'box'  do |f| %>
<div class="field">
<%= f.label 'email:', class: "label"%><br>
<%= f.text_field :email, class: "input" %>
</div>
<div class="field">
<%= f.label 'password:' ,class: "label"%><br>
<%= f.password_field :password, class: "input" %>
</div>
<div class="field">
<%= f.submit 'Log In', class: "input" %>
</div>
<% end %>

会话controller.rb

def create
retailer = Retailer.find_by(email: params[:email])
if retailer.present? && retailer.authenticate(params[:password])
session[:retailer_id] = retailer.id 
redirect_to store_index_path
else
flash.now[:alert] = 'Invalid email or password'
render :new
end
end

如果你想使用涡轮驱动表单提交,你必须返回4xx或5xx响应代码从你的控制器验证错误:

render :new, status: :unprocessable_entity
在你的代码中,它应该是这样的:
def create
retailer = Retailer.find_by(email: params[:email])
if retailer.present? && retailer.authenticate(params[:password])
session[:retailer_id] = retailer.id 
redirect_to store_index_path
else
flash.now[:alert] = 'Invalid email or password'
render :new, status: :unprocessable_entity
end
end

您可以在Turbo文档https://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission中找到更多信息

我想你没有使用turbo_frame_tag来包装表单。

<%= turbo_frame_tag "post" do %>
<%= render 'form', post: @post %>
<% end %>

如果您希望您的表单像hotwire之前一样工作,请将local: true添加到您的表单声明中。换句话说,更改表单声明如下:

form_with url: retailer_log_in_path, class: 'box'

:

form_with url: retailer_log_in_path, class: 'box', local: true  

根据Rails表单帮助文档,form_with默认使用参数remote: true。这激活了表单上的Javascript,错误是因为Javascript正在期待一个特定的(异步)响应;如果您将local: true添加到您的form_with声明中,则表单提交将不是异步的,并且错误应该消失。

最新更新