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

时间:2013-01-07 19:56:06

标签: ruby-on-rails-3 validation nested-attributes http-status-code-406

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

所以在我的控制器中我做的很简单:

 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)

我已经看过堆栈上的多个看似相似的问题,但是

1 个答案:

答案 0 :(得分:0)

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

也许你应该尝试:

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

我的猜测是你的视图正好只需要6个资产,但只能在无效的资产被抛出后找到1-5之后的某个位置,这会导致内部错误。

如果这不能解决问题,我认为您可能需要提供有关资产上运行的验证以及您的观点的更多信息。