Rails 3创建嵌套资源“无路由匹配”错误

时间:2012-04-21 22:53:19

标签: ruby-on-rails-3 routes oncreate nested-resources

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

resources :sports do
  resources :teams
end

我的teams_controller.rb文件包含create 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部分(在app / views / teams文件夹代码的new.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

我希望团队能够从团队建设中节省下来并将我引导到展示团队页面。有人知道/看到我做错了什么吗?

1 个答案:

答案 0 :(得分:2)

你需要通过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.