我肯定我错过了一些非常简单的东西,但我很难理解.我有一个用户注册表单,它可以正确地识别服务器上注册过程中的错误,但它没有将该信息传递回视图以呈现表单上方的错误.
controllers/registrations_controller.rb个
class RegistrationsController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to root_path, notice: "Successfully signed up!"
else
puts 'ERRORS BELOW:'
puts @user.errors.full_messages
render :new
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
views/registrations/new.html.erb个
<%= form_with model: @user, url: signup_path do |f| %>
<% if @user.errors.any? %>
<div class="alert alert-danger">
<% @user.errors.full_messages.each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<% end %>
<div class='mb-3'>
<%= f.label :email %>
<%= f.text_field :email, class:'form-control', placeholder: 'john@test.com' %>
</div>
<div class='mb-3'>
<%= f.label :password %>
<%= f.password_field :password, class:'form-control', placeholder: 'password' %>
</div>
<div class='mb-3'>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class:'form-control', placeholder: 'password' %>
</div>
<div class="mb-3">
<%= f.submit 'Get Started', class: 'btn btn-primary' %>
</div>
<% end %>
routes.rb个
Rails.application.routes.draw do
root to:'main#index'
get "signup", to: 'registrations#new'
post "signup", to: 'registrations#create'
get "about-us", to: 'about#index', as: :about
end
View from my console showing the errors getting printed out serverside个
Started POST "/signup" for 127.0.0.1 at 2023-01-26 10:18:51 -0600
Processing by RegistrationsController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"asdfasdg", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Get Started"}
ERRORS BELOW:
Password confirmation doesn't match Password
Email Must be a valid email address
Rendering layout layouts/application.html.erb
Rendering registrations/new.html.erb within layouts/application
Rendered registrations/new.html.erb within layouts/application (Duration: 3.8ms | Allocations: 2734)
Rendered shared/_navbar.html.erb (Duration: 0.2ms | Allocations: 134)
Rendered shared/_flash.html.erb (Duration: 0.1ms | Allocations: 33)
Rendered layout layouts/application.html.erb (Duration: 54.5ms | Allocations: 17541)
Completed 200 OK in 423ms (Views: 56.7ms | ActiveRecord: 1.1ms | Allocations: 22605)
我试着把它们作为闪光灯通知,甚至在@user.save
失败后也没有渲染:new
,不知道还能try 什么.我在这里找到的许多类似问题的解决方案似乎都是通过将if
/else
块放在create函数中来解决的,但我已经把它放进go 了.不知道我错过了什么.
我还应该补充的是,当我输入正确的邮箱和匹配的密码时,我可以创建一个User
,当我没有通过这两个判断时,它不会创建用户,只是不会将这些错误传递回客户端