1

这是控制器中的方法:

def sort
    case params[:order_param]
    when "title"  
    @cars = Movie.find(:all, :order => 'title')
    when "rating"
    @cars = Movie.find(:all, :order => 'rating')
else "release"
    @cars = Movie.find(:all, :order => 'release_date')
end
    redirect_to cars_path
end

这是视图:

%th= link_to "Car Title", :action => 'sort', :order_param => 'title'
%th= link_to "Rating", :action => 'sort', :order_param => 'rating'
%th= link_to "Release Date", :action => 'sort', :order_param => 'release'

如果我打开索引页面,则会出现以下错误消息:

No route matches {:action=>"sort", :order_param=>"title", :controller=>"cars"}

“rake routes”命令的结果

cars      GET    /cars(.:format)          {:action=>"index", :controller=>"cars"}
          POST   /cars(.:format)          {:action=>"create", :controller=>"cars"}
new_car   GET    /cars/new(.:format)      {:action=>"new", :controller=>"cars"}
edit_car  GET    /cars/:id/edit(.:format) {:action=>"edit", :controller=>"cars"}
car       GET    /cars/:id(.:format)      {:action=>"show", :controller=>"cars"}
      PUT    /cars/:id(.:format)      {:action=>"update", :controller=>"cars"}
      DELETE /cars/:id(.:format)      {:action=>"destroy", :controller=>"cars"}
4

3 回答 3

1

首先把它擦干。不需要那个开关/外壳。

def sort
  @cars = Movie.order(params[:order_param])
  redirect_to cars_path
end

其次,您的文件中似乎没有sort定义路由routes.rb

于 2012-08-07T17:43:45.410 回答
1

您根本不需要排序方法(或重定向)。您可以将该代码放入您的 index 方法中,因为您想显示 index.html.haml (排序“汽车”不应该将您发送到新页面,对吗?)

def index                                                                      
  order_param = params[:order_param]                              
  case order_param                                                                
  when 'title'                                                                 
    ordering = {:order => :title}
  when 'release_date'                                                          
    ordering = {:order => :release_date}
  end

  @cars = Movie.find_all(ordering)
end
于 2012-08-07T19:15:06.827 回答
0

感谢大家的帮助,这是我正在寻找的解决方案(与 mehtunguh 解决方案非常相似)。很抱歉造成误解,我是rails新手。

 def index
    case params[:order_param]
    when "title"  
          @cars = Movie.find(:all, :order => 'title')
    when "rating"
          @cars = Movie.find(:all, :order => 'rating')
    when "release"
          @cars = Movie.find(:all, :order => 'release_date')
    else
          @cars = Movie.all
      end
  end
于 2012-08-07T21:22:30.333 回答