A complete rails beginner here. How do I go about handling a query string in rails? For example for: www.something.com/movie?sort=title
For implementing the the view in the haml file, how can I make it so that clicking on Movie title will send that query string, And more importantly how do I handle it. Where should I implement the function which can access that query string using :params .
I have been on this for more than a day now and could not understand whether that query string will call a controller function or a module from helper.
I hope I was clear enough about the question. Any help will be appreciated.
PS:- there is a movie table with title as one of its column.
Not sure I really understand what you want. Does this suit you?
link_to "My Link", movie_index_path(sort: :title)
Then access param with params[:sort]
?
(Accord movie_index_path
with your routes configuration)
Since your question is not focused let me assume part of your problem.
Assumptions
Then you should tell Rails to route requests with path /movies to movies_controller.rb. This can be done by adding the below lines in config/routes.rb
resources :movies
The if you call www.something.com/movies this will invoke the method index in movies_controller.rb. So you should write some code to display movies here.
class MoviesController < ApplicationController
def index
@movies = Movie.all
end
end
Then you should use app/views/movies/index.haml file to display the movies. There give a link to sort the movies by title.
link_to "Sort by title", movies_path(:sort=>"title")
No when click on the link the user will reach the same index method with params now. You can get the sort value like below.
params[:sort]
SO to support sorting you need to change the controller code little bit.
class MoviesController < ApplicationController
def index
if params[:sort]
@movies = Movie.order('#{params[:sort]} ASC')
else
@movies = Movie.all
end
end
end
I strongly suggest you to go through the http://guides.rubyonrails.org/index.html before asking question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.