2012-04-21 151 views
1

我是Rails的新手,並試圖在嵌套資源中創建子記錄。我的routes.rb文件包含此:Rails 3創建嵌套資源「無路由匹配」錯誤

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部分(在我new.html.erb在app /視圖/支的文件夾代碼是:

<%= 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 

我希望球隊從團隊建設中拯救,並將我引導至展示團隊頁面。有人知道/看到我做錯了什麼嗎?

回答

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. 
+0

那訣竅 - 謝謝。我曾嘗試過這種形式,但是我忽略了控制器中的那個(redirect_to),那就是我搞砸了。 – 2012-04-22 11:49:13