简体   繁体   中英

How do I create a form for an associated model?

I have a company model and a bank_account model.

company has_many bank_accounts and bank_account belongs_to company .

I have a route companies/:company_id/bank_accounts/new which generates a form:

<%= form_for @bank_account do |form| %>
 (form elements here)
<% end %>

But when I get to that page, I get: undefined method bank_accounts_path

Here's my resource routes in routes.rb:

  resources :companies do
    resources :bank_accounts, module: :companies
  end

and my nested bank_account_controller.rb in controllers/companies/

I need my form to post the entered data to the create action. Ruby should know this already right because I'm in the new action? But clearly it doesn't recognise the route.

Let me know if you need more information.

So I was changing a few things to match a similar model for company contacts. I knew these we're the same concept in my application so the same routing and form should work.

First I moved my nested bank_account_controller.rb out of companies and just placed it in app/controllers.

I moved all my bank_account views out of the nested bank_account folder inside views/companies to just app/views/bank_accounts.

I then removed the module companies from my routes.rb so I just had resources :bank_accounts within my companies resources.

Finally, I changed the form_for to: form_with (model: [@company, @bank_account], local: true) do |form| %> form_with (model: [@company, @bank_account], local: true) do |form| %>

Forms constantly trip me up as a somewhat newbie to RoR. I need to understand better what the difference is between for and with:)

You have nested resource, therefore you need

<%= form_for [@company, @bank_account] do |form| %>

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