Rails 4 action routes with simple_form and shallow nested resources

krx picture krx · May 30, 2014 · Viewed 7.8k times · Source
resources :users, shallow: true do
    resources :shoes
end

This gives me two different routes for create and edit

user_shoes_path
shoes_path

In my shoes _form.html.erb if I leave the form tag :url as default I get a missing routes error when I submit a new or updated shoe.

If I supply the url in the form I can get it to work for either the new or the edit update, but I can't get it to work for both.

This works for the new:

<%= simple_form_for :shoe, url: user_shoes_path do |f| %>

This works for the edit, but will fail once it tries the actual update since it redirects to /:param_id:

<%= simple_form_for :shoe, url: shoes_path(@shoe) do |f| %>

How can I make it work for both? Thanks.

Answer

Danny picture Danny · May 30, 2014

You should use

<% = simple_form_for [@user, @shoe] do |f| %>

and let do simple_form do the work...

This case, if there is a @user, simple form will use it (as for a new), if there isn't (like for an edit), simple form won't use it...