rails routes confusing show action with named route

时间:2010-09-17 14:51:03

标签: ruby-on-rails routes

我在使用自己的路由实现列表操作时遇到问题。这就是我所拥有的 (只是重要的部分)  的routes.rb

   map.resources :posts   
   map.login  "login" ,:controller => "user_sessions" ,:action => "new" 
   map.logout "logout" , :controller => "user_sessions" , :action => "destroy"
   map.sort "sort" , :controller => "posts" , :action => "sort"

posts_controller.rb

class PostsController < ApplicationController

 def index
  logger.info "index params:::"+params.inspect
   @posts = current_user.posts.paginate :page => params[:page], :order => 'created_at   DESC'
  end
 end

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

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


  def sort
   logger.info "sort params:::"+params.inspect
   @posts=current_user.posts.paginate(:page=>params[:page],:order=> params[:sort].to_s )
  if request.xml_http_request?
   render :update do |page|
    page.replace_html :posts , :partial => 'post'    
   end
  end
 end


end

我收到此错误  PostsController中的ActiveRecord :: RecordNotFound#show

无法找到ID = sort的帖子。

我认为这是因为应用程序认为当我输入http://localhost:3000/posts/sort时我想显示带有id = sort.how的元素我能解决这个问题吗? 提前谢谢你

1 个答案:

答案 0 :(得分:1)

确实,您处于REST环境中。使用:get方法访问帖子时,默认路由会将请求发送到show操作,并将:id param设置为sort。尝试在路线中定义排序操作​​,例如:

map.resources :posts, :collection => {:sort => :get}

根据您的需要设置动词:由于您只是检索数据,因此看似正确。

然后,删除行

map.sort "sort" , :controller => "posts" , :action => "sort"

您现在应该还有一个不错的网址:sort_posts_url

相关问题