简体   繁体   中英

How can I code a simple_form_for block with nested resources?

I've struggled with the Rails path, so this is what I have right now. For some reason, it works fine for the edit action, but not for the new action.

Route

  resources :distributors do
    resources :user_distributors, as: :users
    resources :distributor_brands, as: :brands
  end

Form declaration:

= simple_form_for @user_distributor, url: distributor_user_path(@distributor, @user_distributor), wrapper: :vertical_input_group do |f|

This link brings up the form for the edit action:

edit_distributor_user_path(@distributor, user_distributor))

However, this link for the does NOT bring up the correct route for the new action:

 new_distributor_user_path(@distributor)

Instead, the form declaration fails with this error:

No route matches {:action=>"show", :controller=>"user_distributors",

It's because the @user_distributor variable has no id value, so that's why it's trying to route to the show action.

How can I code that declaration so that the form works for both new and edit actions?

I have temporarily worked around this by setting the url in the actions, and that does work, but it feels like I'm missing an automatic feature here.

This problem occurs when you try to rename your routes as I did above. When I went back to the ugly route names, everything worked as it was supposed to with the default format:

= simple_form_for [@distributor, @user_distributor]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM