我無法正確使用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」),當頁面生成時,我的@超級英雄是該類的空白實例。
任何幫助?
我認爲問題在於routes.rb能否發佈完整的routes.rb? –
編輯原始帖子以反映整個routes.db文件。 :) –