我无法正确使用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'
这给我留下了“错误:'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(名称:“The Comedian”,true_identity:“Edward Blake”),当页面生成时,我的@superhero是该类的空白实例。
任何帮助?
答案 0 :(得分:0)
编辑:原来这是一个不规则的复数情况。我更新了下面的代码,以显示整体效果。
我的路线: routes.rb
Rails.application.routes.draw do
root to: 'teams#index'
resources :teams do
resources :superheroes
end
end
在&#39; /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
那太糟糕了。