spacerobot
spacerobot

Reputation: 297

How should I set up this form to submit to the correct path?

I have products that have many variants. When I edit and submit the variant I need it to stay connected to the product. So the URl would be localhost/products/1/variants/3/. The way it is right now it is submitting to localhost/variants/3 and errors out because it cannot find the product?

<%= form_with(model: variant, local: true) do |form| %>

Edit. Routes:

  resources :variants
  resources :products do
    resources :option_values
    resources :option_value_variants
    resources :variants do
        collection do
          post :update_positions
        end
      end
  end

Upvotes: 0

Views: 43

Answers (1)

Clara
Clara

Reputation: 2715

When you edit and submit the variant, you don't need to create a nested route. The product_id will already be saved with the variant (from when it was created). So need to use a nested route - you only need nested routes for new and create actions, that is called "shallow nesting". Because only in those two actions you don't have access to the product id in any other way than through the url (params).

The error in your code likely comes from the fact that you created a nested route but you are not giving the product instance to the form:

%= form_with(model: [@product, @variant], local: true) do |form| %>

But as stated above, no need for that here, just change your routes accordingly.

After updating the question:

So for shallow routing your routes should look like this:

resources :variants, only: [:index, :show, :edit, :update, :destroy]
  resources :products do
    ...
    resources :variants, only [:create, :new] do
        collection do
          post :update_positions
        end
      end
  end

Only create and new need to be nested, for the other routes you don't need it.

Upvotes: 1

Related Questions