[英]How do I create a form for an associated model?
I have a company
model and a bank_account
model.我有一家
company
model 和一个bank_account
账户 model。
company has_many bank_accounts
and bank_account belongs_to company
. company has_many bank_accounts
和bank_account belongs_to company
。
I have a route companies/:company_id/bank_accounts/new
which generates a form:我有一条路线
companies/:company_id/bank_accounts/new
生成一个表格:
<%= form_for @bank_account do |form| %>
(form elements here)
<% end %>
But when I get to that page, I get: undefined method bank_accounts_path
但是当我到达那个页面时,我得到:
undefined method bank_accounts_path
Here's my resource routes in routes.rb:这是我在 routes.rb 中的资源路由:
resources :companies do
resources :bank_accounts, module: :companies
end
and my nested bank_account_controller.rb in controllers/companies/和我在控制器/公司/中嵌套的 bank_account_controller.rb
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?
Ruby 应该知道这一点,因为我在新的行动中? 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.所以我改变了一些东西来匹配类似的 model 用于公司联系人。 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.首先,我将嵌套的 bank_account_controller.rb 移出公司,然后将其放在应用程序/控制器中。
I moved all my bank_account views out of the nested bank_account folder inside views/companies to just app/views/bank_accounts.我将所有 bank_account 视图从视图/公司内的嵌套 bank_account 文件夹中移到了 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.然后我从我的 routes.rb 中删除了模块公司,所以我的公司资源中只有资源
:bank_accounts
。
Finally, I changed the form_for to: form_with (model: [@company, @bank_account], local: true) do |form| %>
最后,我将 form_for 更改为:
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. Forms 经常让我成为 RoR 的新手。 I need to understand better what the difference is between for and with:)
我需要更好地理解 for 和 with 之间的区别:)
You have nested resource, therefore you need您有嵌套资源,因此您需要
<%= form_for [@company, @bank_account] do |form| %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.