新手问题 Render action 中传递参数是否可行?

luoyegufei · 2015年11月04日 · 最后由 dc2000 回复于 2015年11月04日 · 2902 次阅读
def new
    authorize! :create, FundRemitBulk
    @allocation_type = params[:allocation_type]
    @fund_remit_bulk = FundRemitBulk.new
    default_customer_corporate_bank =
      CustomerCorporateBank.find(:first,:conditions => {:default_payment => 1})
    @fund_remit_bulk.customer_corporate_bank_id = 
      default_customer_corporate_bank.try(:id)
    @fund_remit_bulk.account_bank = 
      default_customer_corporate_bank.try(:account_bank)
    @fund_remit_bulk.account_number =
      default_customer_corporate_bank.try(:account_number)
    if @allocation_type == "asset_securitization"
      fund_allocations = FundAllocation.abs_allocations
    else
      fund_allocations = FundAllocation.fund_outflow_allocations
    end
    @fund_allocations = fund_allocations.where(:allocated => false)
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @fund_remit_bulk }
    end
  end

上述代码是 FundRemitBulk 的 new,项目中多个模块中都有 new_fund_remit_bulk 的入口,是以 allocation_type 来区分的,即 fund_remit_bulks/new?allocation_type=**; fund_remit_bulk.rb 中对多个字段进行 validates_presence_of 处理,save 失败后,会在相应位置显示非空错误信息(只是需要保证的效果)

下面是 create 的异常捕获

rescue Exception => e
   msg = "新建资金调拨单出错:#{e.message}"
   @fund_remit_bulk.errors.add(:base,msg)
   raise ActiveRecord::Rollback, msg
 end

e.message 显示的是“数据校验未通过”,显然不是我想要的

format.html { redirect_to(new_fund_remit_bulk_path(:allocation_type => type),
                                  :alert => @fund_remit_bulk.errors[:base].join("\n")) }

redirect_to 可以保证 create 失败后停留在正确的新建页面,但是却不能显示非空错误信息,用 render :action => "new"可以实现,但是需要指定 allocation_type。 能否用 render?该如何传参?网上查了不少,但是没看到有谁这么用

用 flash 保存,然后在 view 中使用可行不?

#1 楼 @btc022003 flash.now[:error] = @fund_remit_bulk.errors[:base].join("\n"),render :action => "new"的时候可以,问题是 new 的入口必须要知道 allocation_type,render action 好像不能传递这个参数

form 表单里的字段可以在对应的模型里面做验证的,如果字段为空,提交会报错吧。你干嘛要重定向到新建页面呢?你可以在新建页面给出提示的,不需要转向的。比如你的 form 名字叫 order,那么视图文件对应的应该是,form_for(@order),你发送请求后,根据约定,有一个名为‘order_params’的变量会存储所有的参数值,服务端可以很方便的获取。不需要你通过 URL 拼接的方式传参数。比如你想 在新建页面获取 User 参数,你可以直接通过 params[:user] 获取。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号