验证失败后填充表单

时间:2011-03-05 03:47:58

标签: ruby-on-rails-3 forms

我有report_controller我有两个对象,@ report和@reporte,我想在数据库中保存这两个对象。验证失败时,我希望以渲染的形式填充字段。

我不能只使用@report = ReportMain.new(params[:report_main]),因为我有两个对象和一个params对象。

我使用exportnew动作来显示表单,并使用encreate来保存此表单。

有一些简单的方法可以填充表格吗?

ReportController:

class ReportController < ApplicationController
  before_filter :authenticate_user!
  before_filter :load
  layout "application"

  def load
    @company = Company.find_by_id(current_user.company_id)
    @date = Date.today
    @report = ReportMain.new
    @reporte = ReportE.new
  end

  def index
    list
    render("list")
  end

  def list
    @reports = ReportMain.all
  end

  def exportnew
    render("ennew")
  end

  def encreate

    @report = ReportMain.new
    @reporte = ReportE.new
    @reportparam = params[:report_main]


    @report.waste_id = params[:waste][:code]
    @report.warehouse_id = Warehouse.find_by_user_id(current_user.id).id
    @report.user_id = current_user.id
    @report.company_id = current_user.company_id
    @report.amount = @reportparam[:amount]
    @report.isimport = false
    @report.isfinished = false
    @report.reportnumber =  ReportMain.where(:company_id => current_user.company_id).count.to_i+1
    if @report.save
      @reporte.report_main_id = @report.id
    else
      @report_main = @report
      render("etnew")
      return
    end

    @reporte.vrstaotpada = params[:vrstaotpada]
    @reporte.nacinpakovanja = params[:nacinpakovanja]
    @reporte.ispitivanjebroj = @reportparam[:ispitivanjebroj]
    @reporte.datumispitivanja = @reportparam[:datumispitivanja]
    @reporte.q_pripadnost = @reportparam[:q_pripadnost]
    @reporte.datumpredaje = @date

    if @reporte.save
      redirect_to(:action => 'show', :id => @reporte.id)
      flash[:notice] = "Izveštaj je uspešno kreiran."
    else
      @report_main = @report
      render("etnew")
    end
  end



  def show
    @report = ReportMain.find(params[:id])
    @warehouse = @report.warehouse.name
  end

end

视图以(它是巨大的HTML)开头:

<%= form_for(:report_main, :url => {:action => 'encreate'}) do |f| %>

1 个答案:

答案 0 :(得分:0)

由于您希望在验证失败后填写表单,我建议您通过AJAX提交。有一个jQuery插件可以帮助http://jquery.malsup.com/form/