【发布时间】:2021-07-14 14:41:54
【问题描述】:
我想不通。在模型中没有验证的情况下,表单提交、保存和发布通知都很好。如果我在模型中创建任何验证,例如“validates_presence_of :first_name”,并且将该 first_name 字段留空,那么当我单击表单提交按钮时,该按钮就会冻结,并且在更正该字段后我无法再次按下它。由于页面基本上冻结了,因此页面也没有发布任何错误。
这是我的代码:
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.save
redirect_to root_path
flash[:notice] = "We have received your message and will be in touch soon!"
else
render :new
flash.now[:alert] = "Error! Could not send message, all fields must be filled out properly"
end
end
private
def message_params
params.require(:message).permit(:first_name, :last_name, :email, :body)
end
end
new.html.erb
<%= form_with(model: @message, local: true) do |f| %>
<div>
<%= f.label :first_name %>
<%= f.text_field :first_name %>
</div>
<div>
<%= f.label :last_name %>
<%= f.text_field :last_name %>
</div>
<div>
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div>
<%= f.label :body %>
<%= f.text_area :body %>
</div>
<div>
<%= f.submit 'Send', class: "btn btn-primary" %>
</div>
<% end %>
message.rb
# == Schema Information
#
# Table name: messages
#
# id :bigint not null, primary key
# body :text
# email :string
# first_name :string
# last_name :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Message < ApplicationRecord
validates_presence_of :first_name
end
routes.rb
resources :messages, only: [:new, :create]
【问题讨论】:
标签: ruby-on-rails