简体   繁体   中英

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

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.

Try after changing the below line in your route file

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

to

match "vendors/keyword_search" => "vendors#keyword_search", :as => :vendors_keyword_search_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM