views:

44

answers:

2

I have Exam controller.

In routes.rb there is "resources :exams"

In controller there are REST-like generated methods.

I want to add my own method there:

def search
  @exams = Exam.where("name like ?", params[:q])
end

In view file:

<%= form_tag(search_path, :method => "post") do %>
  <%= label_tag(:q, "Szukaj: ") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Szukaj") %>
<% end %>

I know, there is no results presentation yet, it doesn't work at all at this moment (:

When i go to http://localhost:3000/exams/search it's mapping it to show controller and search is a :id paramether then...

How to get http://localhost:3000/exams/search to run the seach controller?

+3  A: 

You forgot to add route. Put this in routes.rb, before resources :exams

map.search '/exams/search', :controller => :exams, :action => :search

Note, that resources :exams doesn't generate routes for all public methods of the controller, it generates very specific set of routes. You can find more information in the rails routing guide. (see section 3.2 in particular)

Nikita Rybak
clear solution, thank you
matiit
+2  A: 

You'll need to add additional parameters to your mapping. You can add "collection" methods like so:

map.resources :exams, :collection => {:search => :get}

When you rake routes, you'll see that it generates something like so:

search_exams GET    /exams/search(.:format)    {:controller=>"exams", :action=>"search"}
       exams GET    /exams(.:format)           {:controller=>"exams", :action=>"index"}
             POST   /exams(.:format)           {:controller=>"exams", :action=>"create"}
    new_exam GET    /exams/new(.:format)       {:controller=>"exams", :action=>"new"}
   edit_exam GET    /exams/:id/edit(.:format)  {:controller=>"exams", :action=>"edit"}
        exam GET    /exams/:id(.:format)       {:controller=>"exams", :action=>"show"}
             PUT    /exams/:id(.:format)       {:controller=>"exams", :action=>"update"}
             DELETE /exams/:id(.:format)       {:controller=>"exams", :action=>"destroy"}
Chris Heald