0

I have a simple form for Recommendations. REcommendations has_many Assets.

so in my controller I am doing a simple:

 6.times {@recommendation.assets.build}

My issue occurs when I try to save the Recommendation and there are Validation errors. My Create action:

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

running this page and submitting (with validation errors) causes the following log output and a http 406 error

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)

I have looked at multiple questions on stack that seem similar but

TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88

1 Answers1

0

I'm not sure there is enough information to be able to answer with much confidence, but I don't think you want to rebuild exactly 6 times. Depending on your model setup, the validation could nullify one, but not all of the associations.

Perhaps you should try:

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

My guess is that your view is expecting exactly 6 assets but only finding somewhere from 1-5 after the invalid ones were thrown out, and that this is causing an internal error.

If that doesn't fix it, I think you may need to provide more information about what validations are running on assets, and what your view looks like.

Geoff
  • 2,208
  • 1
  • 16
  • 17