Forum: Ruby on Rails Issue with Routes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Memo (Guest)
on 2008-10-06 17:32
(Received via mailing list)
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:               <div id="search">
40:                 <h1 class="mh"><%= "Product Search".t %></h1>
41:                 <div id="search_field">
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:                     <img id='query_indicator' src='/images/
live_tree_loading_spinner.gif' style='display:none;' alt="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
Memo (Guest)
on 2008-10-06 19:05
(Received via mailing list)
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.
This topic is locked and can not be replied to.