【问题标题】:Form submit button not working Rails 6 on validation error表单提交按钮在验证错误时不起作用 Rails 6
【发布时间】: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


    【解决方案1】:

    我不确定您的页面为何冻结。但至于呈现 flash 消息,这不是自动完成的。你必须在你的视图中渲染它,如果你有很多错误要渲染不同的动作,可能是应用程序布局。这是一个例子:

    <% flash.each do |type, msg| %>
      <div>
        <%= msg %>
      </div>
    <% end %>
    

    我喜欢here的解释方式

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 2019-06-06
      • 2011-09-12
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      相关资源
      最近更新 更多