title: How to keep the rails nested resource route url when model save fails?
body: <p><strong>Summary:</strong></p>
  
  <p>I have a nested attribute. I go to route:</p>
  
  <pre><code>/customers/:id/credit_cards/new
  </code></pre>
  
  <p>On the create action, save fails, code does </p>
  
  <pre><code>render :new 
  </code></pre>
  
  <p>This pushes the URL to:</p>
  
  <pre><code>/credit_cards/new
  </code></pre>
  
  <p>How do I make sure the url stays with the customer route?</p>
  
  <p><strong>Details:</strong></p>
  
  <p>I want to use the following routes:</p>
  
  <pre><code># Credit cards should be associated with a customer except
  # potentially on initial creation:
  resources :customers do
    resources :credit_cards, only: [:index, :show, :new, :create, :edit, :update, :destroy, :show]
  end
  # Allow creating a credit card but selecting
  resources :credit_cards, only: [:new, :create]
  </code></pre>
  
  <p>Basically a nested route for when a customer exists and a non-nested route for when I can create and assign a customer in the same view.</p>
  
  <p>I have a single controller at</p>
  
  <pre><code>app/controller/credit_cards_controller.rb
  </code></pre>
  
  <p>In the new and create action I check if I have a customer ID or not</p>
  
  <pre><code>before_action :set_credit_card, only: [:show, :edit, :update, :destroy]
  before_action :set_customer, only: [:index, :show, :create, :new, :edit, :update]
  
  # GET /credit_cards/new                                                                                                                                  
  def new
    @credit_card = if @customer
                     @customer.credit_cards.build rescue CreditCard.new
                   else
                     CreditCard.new
                   end
  end
  
  def create
    @credit_card = CreditCard.new(credit_card_params)
    respond_to do |format|
      if @credit_card &amp;&amp;  @credit_card.save
        format.html { redirect_to on_new_or_update_redirect_location, notice: 'Credit card was successfully created.' }
      else
        # HERE IS THE ISSUE: Figure out how to make sure the url stays as /customers/:id/credit_cards/new instead of /credit_cards/new                                                                 
        format.html { render :new }
      end
    end
  end
  </code></pre>
  
  <p>When there is a validation failure, it re-renders the view, but pushes the URL to</p>
  
  <pre><code>credit_cards/new
  </code></pre>
  
  <p>So I no longer am in the correct URL and customer_id is no longer a parameter.  I assume if I can pass the customer_id it will do the right thing, but I have not found how to do that.</p>