在Ruby on Rails中将视图中的变量传递给控制器

这是控制器中的方法:

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"} 

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

 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 

首先要把它弄干。 没有必要那个开关/箱子。

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

其次,看起来您没有在routes.rb文件中定义的sort路由。

感谢您的帮助,这是我正在搜索的解决方案(非常类似于mehtunguh解决方案)。 对不起,误解,我是铁杆新手。

  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