Rails:嵌套 form_for 错误:'ActionController::UrlGenerationError'

Rails: Nested form_for Errors: 'ActionController::UrlGenerationError'

我无法正确使用 form_for 嵌套资源。

我的模型中有以下设置:

team.rb

class Team < ApplicationRecord
  has_many :superheroes
  accepts_nested_attributes_for :superheroes
end

superhero.rb

class Superhero < ApplicationRecord
  belongs_to :team
end

我的路线:routes.rb

Rails.application.routes.draw do

  root to: 'teams#index'

  resources :teams do
    resources :superheroes
  end

  get '/teams/:team_id/superheroes/:id', to: 'superheroes#show', as: 'team_superheros'

end

'/app/views/superheroes/new.html.erb'

<%= form_for [@team, @superhero] do |f| %>
  <p>Name</p>
  <p><%= f.text_field :name %></p>
  <p>True Identity</p>
  <p><%= f.text_field :true_identity %></p>
  <p><%= f.submit 'SAVE' %></p>
<% end %>

最后,在superheroes_controller.rb

def new
  @team = Team.find_by_id(params[:team_id])
  @superhero = @team.superheroes.build
end

我想我对嵌套 form_for 的理解可能不正确。当我导航到 new_superhero 页面时,我最初收到以下错误:

undefined method `team_superheros_path'

所以我将以下重定向路由添加到 routes.rb

get '/teams/:team_id/superheroes/:id', to: 'superheroes#show', as: 'team_superheros'

这给我留下了带有特定错误的 "Errors: 'ActionController::UrlGenerationError'" 消息:

No route matches {:action=>"show", :controller=>"superheroes", :team_id=>#<Team id: 1, name: "Watchmen", publisher: "DC", created_at: "2016-10-22 04:04:46", updated_at: "2016-10-22 04:04:46">} missing required keys: [:id]

我肯定只是错误地使用了 form_for。我可以通过以下方式在控制台中创建超级英雄:watchmen.superheroes.create(name:"The Comedian",true_identity:"Edward Blake") 当页面生成时,我的@superhero 是一个空白实例class.

有什么帮助吗?

EDIT: 原来是不规则复数的情况。我更新了下面的代码以显示整体有效。

我的路线:routes.rb

Rails.application.routes.draw do

  root to: 'teams#index'

  resources :teams do
    resources :superheroes
  end

end

'/app/views/superheroes/new.html.erb'

<%= form_for [@team,@superhero] do |f| %>
  <p>Name</p>
  <p><%= f.text_field :name %></p>
  <p>True Identity</p>
  <p><%= f.text_field :true_identity %></p>
  <p><%= f.submit 'SAVE' %></p>
<% end %>

superheroes_controller.rb

def new
  @superhero = @team.superheroes.build
end

原来我需要做的是创建一个迁移以将 :superheros 重命名为 :superheroes

class RenameTable < ActiveRecord::Migration[5.0]
  def change
    rename_table :superheros, :superheroes
  end
end

然后添加到inflections.rb:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.irregular 'superhero', 'superheroes'
end

太棒了。