如何在Rails 3中重新构建表单验证错误上的嵌套属性字段?



我有一个简单的推荐表单。建议有许多资产。

所以在我的控制器中我做了一个简单的:

 6.times {@recommendation.assets.build}

当我尝试保存推荐时,出现了验证错误。我的创建操作:

def create
    @recommendation = Recommendation.new(params[:recommendation])
    @recommendation.user_id = current_user.id
    respond_to do |format|
      if @recommendation.save
        format.html { redirect_to thankyou_path, notice: 'Recommendation was successfully created.' }
      else
        6.times {@recommendation.assets.build} if @recommendation.assets.blank?
        render action: "new"
      end
    end
  end

运行此页面并提交(带有验证错误)将导致以下日志输出和HTTP 406错误

Started POST "/categories/1/awards/9/recommendations" for 127.0.0.1 at 2013-01-07 11:50:13 -0800
  Processing by RecommendationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"8PVfFZGa72+3KU/km2weZhNy0rxRfp0Qd+CkHdBoQM8=", "recommendation"=>{"nominee"=>"", "title"=>"", "department"=>"", "award_id"=>"9", "summary"=>"", "accomplishments"=>"", "caption"=>"", "url"=>"", "supervisor"=>"You ARE NOT the nominee’s direct manager / supervisor", "approvals_attributes"=>{"0"=>{"email"=>""}}}, "commit"=>"Save/Submit", "category_id"=>"1", "award_id"=>"9"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
Rendered shared/_recommend_timeline.html.erb (1.2ms)
  Award Load (20.1ms)  SELECT "awards".* FROM "awards" WHERE "awards"."id" = 9 LIMIT 1
Rendered recommendations/_form.html.erb (66.7ms)
Rendered recommendations/new.html.erb within layouts/application (69.8ms)
   (0.5ms)  SELECT COUNT(*) FROM "recommendations" WHERE "recommendations"."user_id" = 2
   (0.6ms)  SELECT COUNT(*) FROM "approvals" WHERE "approvals"."email" = 'tj@ravennainteractive.com' AND "approvals"."approved" IS NULL
Completed 406 Not Acceptable in 556ms (Views: 188.6ms | ActiveRecord: 31.5ms)

我看过几个关于堆栈的问题,看起来很相似,但是

我不确定是否有足够的信息能够自信地回答,但我不认为你想要重建6次。根据您的模型设置,验证可以使一个关联无效,但不能使所有关联无效。

也许你应该试试:

(6-@recommendation.assets.count).times {@recommendation.assets.build}

我的猜测是,您的视图期望正好6个资产,但在无效的资产被丢弃后只找到1-5个资产,并且这导致内部错误。

如果这还不能解决问题,我认为你可能需要提供更多的信息,关于在资产上运行的验证,以及你的视图是什么样子的

相关内容

  • 没有找到相关文章

最新更新