2012-04-21 126 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