Rails 3 创建嵌套资源 "No route matches"错误



我是Rails的新手,正在尝试在嵌套资源中创建子记录。我的routes.rb文件包含以下内容:

resources :sports do
  resources :teams
end

我的 teams_controller.rb 文件包含用于创建 def 的以下内容:

def create
@sport = Sport.find(params[:sport_id])
@team = @sport.teams.build(params[:team_id])
respond_to do |format|
  if @team.save
    format.html { redirect_to @team, notice: 'Team was successfully created.' }
    format.json { render json: @team, status: :created, location: @team }
  else
    format.html { render action: "new" }
    format.json { render json: @team.errors, status: :unprocessable_entity }
  end
end

结束

我的 _form.html.erb 部分(在我的新.html.erb 中的应用程序/视图/团队文件夹代码中是:

<%= form_for(@team) do |f| %>
<% if @team.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@team.errors.count, "error") %> prohibited this team from being saved:</h2>
  <ul>
  <% @team.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
 <div class="field">
 <%= f.label :city %><br />
 <%= f.text_field :city %>
  </div>
  <div class="actions">
    <%= f.submit %>
</div>
<% end %>

当我尝试在表单上提交时,出现以下错误:

"No route matches [POST] "/teams" "

最后,当我耙路线时,我得到这个:

sport_teams GET    /sports/:sport_id/teams(.:format)          teams#index
            POST   /sports/:sport_id/teams(.:format)          teams#create
new_sport_team GET    /sports/:sport_id/teams/new(.:format)      teams#new
edit_sport_team GET    /sports/:sport_id/teams/:id/edit(.:format) teams#edit
 sport_team GET    /sports/:sport_id/teams/:id(.:format)      teams#show
            PUT    /sports/:sport_id/teams/:id(.:format)      teams#update
            DELETE /sports/:sport_id/teams/:id(.:format)      teams#destroy
     sports GET    /sports(.:format)                          sports#index
            POST   /sports(.:format)                          sports#create
  new_sport GET    /sports/new(.:format)                      sports#new
 edit_sport GET    /sports/:id/edit(.:format)                 sports#edit
      sport GET    /sports/:id(.:format)                      sports#show
            PUT    /sports/:id(.:format)                      sports#update
            DELETE /sports/:id(.:format)                      sports#destroy
我希望团队从团队

构建中保存并将我引导到显示团队页面。有谁知道/看到我做错了什么?

您需要传递form_for一系列运动和团队:

<%= form_for([@sport, @team]) do |f| %>

redirect_to相同:

format.html { redirect_to [@sport, @team], notice: 'Team was successfully created.' }

从 Rails API:

If your resource has associations defined, for example, 
you want to add comments to the document given that the routes
are set correctly:
<%= form_for([@document, @comment]) do |f| %>
 ...
<% end %>
Where 
  @document = Document.find(params[:id]) 
and 
  @comment = Comment.new.

相关内容

最新更新