1

I'm trying to build a nested form that will create a new user and subscribe them to a plan.

When I hit "Enroll" I get the following error:

Validation failed: Plan subscriptions user can't be blank

I've double and triple checked everything below and am not sure what's wrong at this point. Any idea why the subscription is not being associated to the new user record?

Here's my code:

User.rb

class User < ActiveRecord::Base
  attr_accessible ..., :plan_subscriptions_attributes

  has_many :plan_subscriptions, dependent: :destroy      

  accepts_nested_attributes_for :plan_subscriptions

PlanSubscriptions.rb

class PlanSubscription < ActiveRecord::Base

  belongs_to :user

Plan_Subscriptions#new

  def new
      @plan = Plan.find(params[:plan_id])
      @user = User.new
      @user.plan_subscriptions.build
  end

Plan_Subscriptions/New.html

<%= form_for @user do |f| %>
    <fieldset>

        <%= f.text_field :first_name, :label => false, :placeholder => 'First Name', :required => false %>
        <%= f.text_field :last_name,  :label => false, :placeholder => 'Last Name', 

          <%= f.fields_for :plan_subscriptions do |builder| %>
            <%= builder.hidden_field :plan_id, :value => @plan.id %>
           <% end %>


        <%= f.submit 'Enroll', :error => false %>
    </fieldset>
<% end %>
pejmanjohn
  • 1,057
  • 3
  • 12
  • 26

1 Answers1

0

Plan wont have an id at this point in the execution so I wouldn't use that. Try removing the line:

<%= builder.hidden_field :plan_id, :value => @plan.id %>

@plan.id will be nil, so it will overwrite the automatically built object and thus fail the validation.

Then attempt to submit the form again. Try adding a valid form element for the plan subscription if you want the user to set something in the subscription.

Kieran Andrews
  • 5,845
  • 2
  • 33
  • 57
  • Sorry about that, shouldn't have hidden that line. I can confirm that `@plan` is valid. It gets set in the controller based on a url parameter. I can confirm that `@plan.id` gets set to "2" (a valid ID). So that doesn't seem to be it. The error is complaining about a blank user id. – pejmanjohn Jan 28 '14 at 00:15