Reputation: 632
How do I use a model in my config/routes.rb file? what I want to accomplish is the following routes.
match '/:name', :topic => Post.where(:topic => name).first, :to => 'posts#search'
is this possible?
Upvotes: 0
Views: 62
Reputation: 9712
@Michael is right - don't put database code in a routes file. Of course, it is possible but it's really going against rails conventions and principles.
A better approach would be:
resources :posts do
collection { get :search }
end
Your search form would look something like this:
= form_tag(search_posts_path, :method => :get) do
= text_input_tag(:q)
And your controller:
def search
@posts = Post.where("body like ?", "%#{params[:q]}%")
end
Note that you would normally use pagination (will_paginate or kaminari) too, and might want to consider a full-text search engine like sphinx.
Upvotes: 1
Reputation: 96464
Routes are to controllers not models. Plus I would recommend not putting the topic selection in the routes like that. Most of getting rails right is doing the right thing in the right area.
Standards and REST based systems tend to me that they are often the same, e.g. a Posts controller manages records for the Post model with views in app/views/posts but they are different things.
Having the route /:name
to go to posts#search is ok, however I feel that getting the topic in question should be done within the posts controller. If the search is within posts you could use nested resources on your routes, something like:
resources: :topics do
resources :posts, :member => :search
end
Upvotes: 1