PostsController#中的ActiveRecord :: RecordNotFound显示单击链接

时间:2011-12-14 15:20:49

标签: ruby-on-rails ruby ruby-on-rails-3 routing ruby-on-rails-3.1

<li><%= link_to('More Commented', posts_morecommented_path) %></li>

错误

ActiveRecord::RecordNotFound in PostsController#show

Couldn't find Post with id=morecommented

Request

Parameters:

{"id"=>"morecommented"}

我在哪里做错了?

postscontroller #show action

def show      @post = Post.find(params[:id])      ...         end

morecommented.html.erb

<% @moreCommented.each do |t| %>
    <%= link_to t.title, :controller => '/posts', :action => 'show', :id => t.id %><br/>
<% end %>

rake routes

post GET    /posts/:id(.:format)           {:action=>"show", :controller=>"posts"}
....      
posts_morecommented        /posts/morecommented(.:format) {:controller=>"posts", :action=>"morecommented"}

routes.rb中:

  resources :posts
  match "posts/:id/categ" => "posts#categ"
  match "posts/:id/tag_posts" => "posts#tag_posts"
  match "posts/searcharchive" => "posts#searcharchive"
  match "posts/morecommented" => "posts#morecommented"

2 个答案:

答案 0 :(得分:5)

在资源调用之前移动匹配

match "posts/morecommented" => "posts#morecommented"
resources :posts

或者你可以做

resources :posts do
   get :morecommented, on: :collection
end

答案 1 :(得分:2)

您的问题出在routes.rb文件中,因为路由从上到下匹配posts/morecommented匹配posts/:id操作,params[:id]等于morecommented Gerry提到的一个解决方案是在match "posts/morecommented" => "posts#morecommented"文件中调用resources :posts之前更改顺序并移动routes.rb,另一个解决方案是在:id中设置posts/:id的要求1}}路线。