Rails嵌套属性 - URL错误

时间:2012-05-17 20:57:21

标签: ruby-on-rails ruby-on-rails-3 nested-attributes

我正在开展一项小工作,以创建帖子并按类别划分。我有一切正常,但在我的index.html中,我收到以下与我的链接相关的路由错误。

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

在posts / 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

当我运行rake路线时,我得到:

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

我的索引中有一些错误导致应用程序崩溃,因为我可以访问并查看这些内容而没有任何问题:

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

有人可以帮帮我吗?提前谢谢。

1 个答案:

答案 0 :(得分: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