I simple search controller that stores search history, should I use resource routing or non-resource?
I am learning rails and am toying with a simple web-app that integrates with flickr to search photos based on user given criteria and store the query in a search history table.
I am seeking the b开发者_开发百科est or 'rails' way of handling this. Should I setup a controller and non-resource routes that handle the search and store the data in a custom table; or should I create a resource for queries with a resource route and an additional path for search?
Lemme refactor a bit:
rails g controller searches
This neat rule will allow you to use nifty action-per-resource searches controller:
# config/routes.rb
get 'search/:action' => 'searches#:action'
Here's simplified version of such one:
class SearchesController < ApplicationController
def foos
search do
Foo.where :name => params[:q]
end
end
def bars
search do
Bar.where :title => params[:q]
end
end
private
def search(&block)
if params[:q]
@results = yield if block_given?
respond_to do |format|
format.html # resources.html.erb
format.json { render json: @results }
end
else
redirect_to root_url, :notice => 'No search query was specified.'
end
end
end
Examples of URL queries:
/search/foos?q=baz
/search/bars?q=baz
My thoughts:
In config/routes.rb:
match '/search/:query' => 'search#search', :as => 'search'
Create a SearchController
:
rails generate controller search
In app/controllers/search_controller.rb:
class SearchController < ApplicationController
def search
# Use params[:query] to perform the search
end
end
For example, a query for "apples" would appear as: http://example.com/search/apples
You can generate links to queries with: search_path('apples')
精彩评论