Joe Joe - 16 days ago 6
Ruby Question

In rails "get 'vendors/keyword_search', to: 'vendors#keyword_search'" runs "'vendors#show'"

In a rails app, I am trying to setup a route to a keyword search page. I am trying to pass the following test:

scenario 'can perform a keyword search' do
click_link 'Search'
click_link 'Keyword search'
expect(current_path).to eq '/vendors/keyword_search'
fill_in 'search', with: vendor_one.email
click_button 'Search suppliers'
expect(page).to have_content vendor_one.email
expect(page).not_to have_content vendor_two.email
end


So far I have:

in /views/vendors/index.html.erb

<div class='col-xs-3'>
<p><%= link_to 'Keyword search', vendors_keyword_search_path %></p>
</div>


in /routes.rb

root to: 'homepage#index'

resources :buyers, :vendors

get 'vendors/keyword_search', to: 'vendors#keyword_search'


in /controllers/vendors_controller.rb

class VendorsController < ApplicationController
def index
@vendors = Vendor.all
end

def show
@vendor = Vendor.find(params[:id])
end

def keyword_search
end
end


I then have a /views/vendors/keyword_search.html.erb with the following:

<div id='main container' class='container-fluid'>
<div class='row'>
<div class='col-xs-3'>
</div>
<div class='col-xs-6'>
<h1>suppliers#keyword_search</h1>
</div>
<div class='col-xs-3'>
</div>
</div>
</div>


My issue seems to be coming after a click on the 'Keyword search' link. Rather than running
vendors#keyword_search
and loading the '/views/vendors/keyword_search.html.erb' template, my path helper
vendors_keyword_search_path
attempts to run
vendors#show
resulting in the following error message (note the first line of stack trace included):

1) Buyers searching vendors can perform a keyword search
Failure/Error: @vendor = Vendor.find(params[:id])

ActiveRecord::RecordNotFound:
Couldn't find Vendor with 'id'=keyword_search
# ./app/controllers/vendors_controller.rb:7:in `show'


Help on this would be greatly appreciated, but most of all I really want to understand why it's running
show
and not
keyword_search
.

Thanks

RLT RLT
Answer

Rails processes the routes sequentially. So it matches vendors/keyword_search to vendors#show as that is the first "match" in the routes. It then treats keyword_search as the :id parameter for the show route.

So you should place your route for keyword_search above the resources.