2016-10-22 90 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 

這太麻煩了。

相關問題