Matt
Matt

Reputation: 8982

pass a variable from view to controller in Ruby on Rails

This is the method in the controller:

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

This is the view:

%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'

If I open the index page, this error message appears:

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

Result of the "rake routes" command

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

Upvotes: 1

Views: 3979

Answers (3)

Matt
Matt

Reputation: 8982

Thanks for help guys, this is solution i was searching (very similar to mehtunguh solution). Sorry for misunderstandings, I'm new to 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

Upvotes: 0

krethika
krethika

Reputation: 4496

You do not need a sort method (or a redirect) at all. You can put that code into your index method since you want to display index.html.haml (sorting 'cars' should not send you to a new page, right?)

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

Upvotes: 1

JGrubb
JGrubb

Reputation: 889

Dry it up first of all. There's no need for that switch/case.

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

Secondly, it looks like you don't have a sort route defined in your routes.rb file.

Upvotes: 1

Related Questions