Issue with Routes


#1

I want a form on my home page to be handled by a different controller
(buy_controller) but I’m having issues. The code works fine when I
have the form under the “buy” views

I’m pretty new to Rails. I’ve tried different ways of doing this but
I can’t seem to figure it out. The latest error is doesn’t let me
load the home page.

Error


ActionController::RoutingError in Home#index

Showing home/index.rhtml where line #42 raised:

buy_url failed to generate from
{:controller=>“buy”, :action=>“search_for_product”}, expected:
{:controller=>“buy”, :action=>“show”}, diff: {:action=>“show”}

Extracted source (around line #42):

39:


40:

<%= “Product Search”.t %>


41:

42: <% form_for :buy, :url => buy_path(:action =>
‘search_for_product’), :html => { :id => ‘search_form’ } do |form| %>
43: <%= form.text_field :query, :size => 70 -%>
44: <%= submit_tag “Search”.t %>
45: loading

Here is my code:

routes.rb


map.resources :buy

/home/index.rhtml


<% form_for :buy, :url => buy_path(:action =>
‘search_for_product’), :html => { :id => ‘search_form’ } do |form| %>
<%= form.text_field :query, :size => 70 -%>
<%= submit_tag “Search” %>
<% end %>

buy_controller


def search_for_product
if params[:buy][:query].blank?

end
if @fail
flash[:error] = @err_msg
redirect_to :back
else
respond_to do |format|
format.html { render :template => ‘buy/search’,
:layout => ‘buy’ } # search.rhtm
end
end
end


#2

I finally figured out the problem.

I added a named route
map.buy_search ‘/buy/search_for_product’, :controller =>
“buy”, :action => ‘search_for_product’

and changed /home/index.rhtml


<% form_for :buy, :url => buy_search_path, :html => { :id =>
‘search_form’ } do |form| %>
<%= form.text_field :query, :size => 70 -%>
<%= submit_tag “Search” %>
<% end %>

I really recommend using Railscasts (http://railscasts.com) by Ryan
Bates for anyone else that’s new to Rails.