alexZ
alexZ

Reputation: 189

Rails link-to custom action fail to work

I'm working on assignment 2 problem 3 for saas class. I'm totally a rails beginner, and having trouble with the problem.

The assignment asks you to make column name "movie title" a link, which sort the movies by name

What I'm doing is make "movie title" a link:

%th#title_header= link_to 'Movie Title', :controller => 'movies', :action => 'sort_by_title'

Add a custom action to movies_controller:

def sort_by_title
  @movies = Movie.find(:all, :order => "title")
  render movies_path
end

Then rails give me error:

No route matches {:controller=>"movies", :action=>"sort_by_title"}

Then I say ok and add it to the route file:

match '/movies?sort_by_title', :to => 'movies#sort_by_title'

Now the index page renders fine but nothing happens when click the movie_title link.

Am I on the right path or totally wrong?

The rake routes prints:

movies GET    /movies(.:format)               {:action=>"index", :controller=>"movies"}
       POST   /movies(.:format)               {:action=>"create", :controller=>"movies"}
new_movie GET    /movies/new(.:format)           {:action=>"new", :controller=>"movies"}
edit_movie GET    /movies/:id/edit(.:format)      {:action=>"edit", :controller=>"movies"}
movie GET    /movies/:id(.:format)           {:action=>"show", :controller=>"movies"}
       PUT    /movies/:id(.:format)           {:action=>"update", :controller=>"movies"}
       DELETE /movies/:id(.:format)           {:action=>"destroy", :controller=>"movies"}
              /movies?sort_by_title(.:format) {:controller=>"movies", :action=>"sort_by_title"}

Thank you

Upvotes: 1

Views: 1581

Answers (2)

Andrew Marshall
Andrew Marshall

Reputation: 97024

Why create a route for this when it's really just a GET parameter? It's not a new action either, it's still displaying all movies, just in a different manner.

Modify your index action to do something like this:

def index
  @movies = Movie.scoped
  @movies = @movies.order('title') if params['sort'] == 'title'
end

and then update your link:

link_to 'Movie Title', movies_path(:sort => 'title')

Resist the temptation to do just Movie.order(params['sort']) if params['sort'], as that opens up a potential SQL injection and, if not, just allows an attacker to discover all the columns in your table. It also has the potential to fail if the user just inputs a bad sort value in the URL.

Upvotes: 2

Yanhao
Yanhao

Reputation: 5294

Should it like this:

match '/movies/sort_by_title', :to => 'movies#sort_by_title'

Upvotes: 1

Related Questions