简体   繁体   中英

Rails form builder with admin namespace

The code below works well to create new transactions on the Invoice show view. It however doesn't work when in admin namespace. ie /admin/invoices/1/ but works on /invoices/1/

show.html.erb

<%= form_for([@invoice, @invoice.transactions.build]) do |form| %>
....
transactions form input

routes.rb

resources :invoices do
  resources :transactions
end

When calling form_for in a namespace route like /admin/invoices/1/ , Rails will automatically append admin to your route. In other words, form_for([@invoice, @invoice.transactions.build]) would POST to a route like /admin/invoice/:id/transactions/ rather than /invoice/:id/transactions/ .

To fix, explicitly set the URL of the form and use a route helper method to infer the correct route:

form_for(@invoice, url: invoice_transaction_url(@invoice.id))

Note that you may need to replace invoice_transaction_url with the correct route. Use rake routes to find the helper method that corresponds to the desired controller POST action.

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