Nick
Nick

Reputation: 3160

Nested signup form does not render correctly after invalid submission

I have a combined/nested signup form, which registers a new organization plus a member (two models with a 1:many relationship).

When submitting invalid information to the form (that is, I fill in invalid info for the organization and no info at all for the member) it should render the combined signup form again with the error message. Instead in this scenario after submitting the invalid information, it only renders the part of the signup form for signing up the organization (without the member part of the form). If I enter invalid information for both organization and member, then it does render correctly the full combined form.

Does anyone have an idea what is wrong with the code?


The controller includes:

  def new
    if (logged_in?)
      flash[:danger] = "You're already logged in"
      redirect_to root_url
    end
    @organization = Organization.new
    @member = @organization.members.build
  end

  def create
    @organization = Organization.new(organizationnew_params)
    if @organization.save
      @organization.members.each do |single_member|
        single_member.send_activation_email
      end
      flash[:success] = "Please check your email to activate your account."
      redirect_to root_url
    else                            
      render 'new'    # This is the relevant render line.
    end
  end

The new view:

<%= render partial: "registrationform", locals: { url: organizations_path } %>

The partial (registrationform):

<% if local_assigns.has_key? :url %>

  <%= form_for @organization, url: url do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <h4>Details of the organization:</h4>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.fields_for :members do |p| %>
      <h4>Your personal details:</h4>
      <%= p.email_field :email, class: 'form-control' %>
      <%= p.password_field :password, class: 'form-control' %>
      <%= p.password_field :password_confirmation, class: 'form-control' %>
    <% end %>
    <%= f.submit "Sign up" %>
  <% end %>

<% else %>
  <%= flash.now[:danger] = "Error: no url defined" %>
<% end %>

Routes:

get 'signup/organization' => 'organizations#new', as: 'register'

Upvotes: 1

Views: 55

Answers (1)

Mario
Mario

Reputation: 1359

In your new action, you are doing @organization.members.build, which is not in your edit action. When the validation fails, it will render your new action, but won't run your new action. You could try putting @organization.members.build in the else clause of your create action like:

else
  @organization.members.build if @organization.members.blank?
  render 'new'
end

Upvotes: 1

Related Questions