Last active
August 29, 2015 14:01
-
-
Save andywenk/a1fa786615a16c08499f to your computer and use it in GitHub Desktop.
simple example for implementing a search in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchController | |
# GET /search/new | |
def new | |
# add the search form here with form_for @posts. | |
# the view is placed in app/views/search/new.html.erb | |
@posts = Posts.new | |
end | |
# here you request the posts table with the given param from the search form | |
# but before check what you have received, so that there is only a string | |
# you can work with (you are not implementing a full text search here!) | |
# the view is placed in app/views/search/create.html.erb | |
# POST /search/create | |
def create | |
query_id = query_id_from_params(params) | |
unless query_id.blank? | |
@post = Posts.find(query_id) | |
redirect_to(@post) # this will redirect to show | |
else | |
# show the new page again because there was no result | |
# you can add a message with the flash mechanism | |
render :new | |
end | |
end | |
# GET /search/show/1 | |
def show | |
@posts = Posts.find(params[:id]) | |
# your result page | |
end | |
private | |
# this method should be place in a SearchModel or sth. like that | |
def query_id_from_params(params) | |
# check the string from params[:search_field] and return it or e.g. an empty string | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment