如果验证失败,则渲染另一个控制器的操作

时间:2018-03-23 13:20:21

标签: ruby-on-rails validation

几乎在我的应用程序的每个页面上,我都有一个部分表单,我可以创建一个Offer。为此,我有offers_controller create行动:

class OffersController < ApplicationController

  def create
    offer = Offer.new(offer_params)
    if offer.save
      redirect_to confirmation_offer_path
    else
      redirect_back(fallback_location: root_path, alert: 'Something went wrong.')
    end
  end

  private

  def offer_params
    params.permit(:company, :first_name, :last_name, :email, :phone, :subject, :message)
  end

end

如果验证失败,我需要显示错误消息。由于此表单位于每个页面上,因此我不知道如何呈现适当的操作。如果我只有一个带有此表单的页面,控制器将如下所示:

class OffersController < ApplicationController

  def new
    @offer = Offer.new
  end

  def create
    @offer = Offer.new(offer_params)
    if @offer.save
      redirect_to confirmation_offer_path
    else
      render :new
    end
  end

  def offer_params
    params.require(:offer).permit(:company, :first_name, :last_name, :email, :phone, :subject, :message)
  end

end

那么,如何呈现动作以显示错误消息?谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用Flash消息:

http://api.rubyonrails.org/classes/ActionDispatch/Flash.html

然后,在您的应用程序布局文件中,您可以处理此问题,例如:

<% flash.each do |key, value| %>
  <div class="alert alert-<%= key %> alert-dismissable fade in"><%= value %>
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  </div>
<% end %>