2012-05-17 73 views
0

我正在創建一個小任務來創建帖子並按類別劃分它們。我有一切工作,但在我的index.html我收到以下與我的鏈接路由錯誤。Rails嵌套屬性 - URL錯誤

No route matches {:action=>"show", :controller=>"posts"} 
No route matches {:action=>"edit", :controller=>"posts"} 
undefined method `post_path' for #<#<Class:0x007fd3097f0ce0>:0x007fd3097c9370> 

在帖子/ index.html.haml我:

- @category.posts.each do |post| 
     %tr 
      %td= post.title 
      %td= post.description 
      %td= post.user_id 
      %td= post.category_id 
      %td= link_to 'Show', category_post_path //gives first error 
      %td= link_to 'Edit', edit_category_post_path //gives second error 
      %td= link_to 'Destroy', post, 
      :confirm => 'Are you sure?', :method => :delete //gives third error 

在routes.rb中我有:

resources :categories do 
    resources :posts 
    end 

當我運行耙途徑獲得:

categories_index GET /categories/index(.:format) categories#index     
category_posts GET /categories/:category_id/posts(.:format)  posts#index 
        POST /categories/:category_id/posts(.:format)   posts#create 
new_category_post GET /categories/:category_id/posts/new(.:format)  posts#new 
edit_category_postGET /categories/:category_id/posts/:id/edit(.:format) posts#edit 
category_post  GET /categories/:category_id/posts/:id(.:format)  posts#show 
        PUT /categories/:category_id/posts/:id(.:format)  posts#update 
        DELETE /categories/:category_id/posts/:id(.:format)  posts#destroy 

我的索引有一些問題是maki因爲我可以訪問和看到這些沒有問題:

/categories/:category_id/posts/:id (equivalent to show) 
/categories/:category_id/posts/:id/edit (equivalent to edit) 

有人可以幫我嗎?先謝謝你。

回答

1

URL助手需要知道您感興趣的類別和帖子,因此您必須傳遞特定類別並將對象作爲參數傳遞給助手。我認爲這些應該工作:

 %td= link_to 'Show', category_post_path(@category,post) //gives first error 
     %td= link_to 'Edit', edit_category_post_path(@category,post) //gives second error 
+0

非常感謝你,我感謝你的幫助!那些工作很好.. –