EastsideDev
EastsideDev

Reputation: 6659

Not routing to expected controller action, Rails

Rails 6

In my config/routes.rb, I have:

match "customers/current_customers" => "customers#current_customers", as: :current_customers, via: [:get]

And in my dropdown menu, I have:

.dropdown-menu aria-labelledby="Customers"
  button.dropdown-item type="button"
    = link_to current_customers_path
      = t('current_customers')

My routes, show:

customers GET /customers(.:format) customers#index 
POST /customers(.:format) customers#create 
new_customer GET  /customers/new(.:format) customers#new 
edit_customer GET  /customers/:id/edit(.:format)   customers#edit 
customer GET  /customers/:id(.:format) customers#show 
PATCH  /customers/:id(.:format) customers#update 
PUT  /customers/:id(.:format) customers#update 
DELETE /customers/:id(.:format) customers#destroy 
current_customers GET  /customers/current_customers(.:format)   customers#current_customers 

And. in controllers/customers_controller.rb, I have:

def current_customers
  @customers = Customer.current_customers
end

When I select the menu item, the development log tells me:

Started GET "/customers/current_customers" for 127.0.0.1 at 2020-03-13 18:04:15 -0700
Processing by CustomersController#show as HTML
  Parameters: {"id"=>"assigned_customers"}

Which fails, obviously, with the following message:

ActiveRecord::RecordNotFound (Couldn't find Customer with 'id'=current_customers):  
app/controllers/customers_controller.rb:86:in `set_customer'

Why is it going to the show action, instead of the current_customers?

Upvotes: 0

Views: 26

Answers (1)

Josh Brody
Josh Brody

Reputation: 5363

Your routes get processed from the top-down, and priority is given to those at the top.

Assuming you also have a resources :customers, and then below this is the match ..., prioritizing the match should get you the result you're looking for. Additionally, using collection:

match "customers/current_customers" => "customers#current_customers", as: :current_customers, via: [:get]
resources :customers

or (preferred)

resources :customers do 
  collection do 
    get :current_customers
  end 
end

Upvotes: 1

Related Questions