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

sort メソッド (またはリダイレクト) はまったく必要ありません。index.html.haml を表示したいので、そのコードを index メソッドに入れることができます ('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
于 2012-08-07T19:15:06.827 に答える
0

助けてくれてありがとう、これは私が探していたソリューションです(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
于 2012-08-07T21:22:30.333 に答える