spierepf
spierepf

Reputation: 2916

How do I create a rails controller action?

My rails app has a single CustomerSelectionController, with two actions:

index: which shows a form where the user can enter customer information and select: which just displays a static page.

class CustomerSelectionController < ApplicationController
  def index
  end

  def select
  end
end

I've created an entry in my routes.rb file:

  resources :customer_selection

and the form in the index view looks like:

<h1>Customer Selection</h1>

<%= form_tag("customer_selection/select", :method => "get") do %>
  <%= submit_tag("Select") %>
<% end %>

however when I click on the Select button in the browser, all I get is:

Unknown action

The action 'show' could not be found for CustomerSelectionController

I'm not sure why it is trying to perform an action called show? I haven't defined or referenced one anywhere.

Upvotes: 0

Views: 183

Answers (1)

user229044
user229044

Reputation: 239230

I'm not sure why it is trying to perform an action called show? I haven't defined or referenced one anywhere.

Yes you have. That's what resources does. It defines the seven default RESTful routes: index, show, new, create, edit, update and destroy. When you route to /customer_selection/select, the route that matches is "/customer_action/:id", or the "show" route. Rails instantiates your controller and attempts to invoke the "show" action on it, passing in an ID of "select".

If you want to add a route in addition to those, you need to explicitly define it, and you should also explicitly state which routes you want if you don't want all seven:

resources :customer_selection, only: %w(index) do
  collection { get :select }
  # or
  # get :select, on: :collection
end

Since you have so few routes, you can also just define them without using resources:

get "/customer_selection" => "customer_selection#index"
get "/customer_select/select" 

Note that, in the second route, the "customer_select#select" is implied. In a route with only two segments, Rails will default to "/:controller/:action" if you don't specify a controller/action.

Upvotes: 1

Related Questions