2016-10-22 87 views
0

我无法正确使用form_for我的嵌套资源。Rails:嵌套form_for错误:'ActionController :: UrlGenerationError'

,我有以下设置在我的模型:

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' 

这让我用“错误: '的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(名称:“喜剧演员”,true_identity:“Edward Blake”),当页面生成时,我的@超级英雄是该类的空白实例。

任何帮助?

+0

我认为问题在于routes.rb能否发布完整的routes.rb? –

+0

编辑原始帖子以反映整个routes.db文件。 :) –

回答

0

编辑:原来是一个不规则的复数情况。我更新了下面的代码以显示总体工作情况。

我的路线:的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 

原来是我需要做的是建立一个移植到重命名:超级英雄到:超级英雄

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 

这太麻烦了。

相关问题