Rails从无效表单中恢复?

时间:2011-02-21 14:05:20

标签: ruby-on-rails validation forms recover rescue

我有一个Rails 2.3应用程序。

我目前在我的模型中有以下验证:

validates_presence_of :jobno, :companyname

我有以下控制器:

# POST /kases
# POST /kases.xml
  def create
    @company = Company.find(params[:kase][:company_id])
    @kase = @company.kases.create!(params[:kase])

    respond_to do |format|
        UserMailer.deliver_makeakase("EMAILADDRESS", "Highrise", @kase) if params[:sendtohighrise]
        UserMailer.deliver_makeakaseteam("EMAILADDRESS", "Highrise", @kase) if params[:notify_team_of_creation]
        @kase.delay.create_freeagent_project(current_user) if params[:send_to_freeagent]

        #flash[:notice] = 'Case was successfully created.'
        flash[:notice] = fading_flash_message("Case was successfully created.", 5)
    end  
        format.html { redirect_to(@kase) }
        format.xml  { render :xml => @kase, :status => :created, :location => @kase }
  end

因此,当您尝试创建一个不包含jobno或companyname的新记录时,我正确地收到以下错误消息:

ActiveRecord::RecordInvalid in KasesController#create
Validation failed: {{errors}}

我已经了解了恢复能力,但我不确定如何/在何处使用它。我已经阅读了一些关于拯救表格内容的文件。我正在努力使表单保持原样 - 输入内容 - 但在表单上显示错误。

我读过的其中一个文件是http://apidock.com/rails/ActiveRecord/RecordInvalid

我不想记录错误,只是告诉用户问题是什么,以便他们可以再试一次。

这可能吗?

谢谢,

丹尼

1 个答案:

答案 0 :(得分:2)

def create
  @company = Company.find(params[:kase][:company_id])
  @kase = @company.kases.new(params[:kase])

  if @kase.save
    UserMailer.deliver_makeakase("EMAILADDRESS", "Highrise", @kase) if params[:sendtohighrise]
    UserMailer.deliver_makeakaseteam("EMAILADDRESS", "Highrise", @kase) if params[:notify_team_of_creation]
    @kase.delay.create_freeagent_project(current_user) if params[:send_to_freeagent]
    redirect_to @kase
  else  
    render :new
  end
end