[英]How do I create a rails controller action?
My rails app has a single CustomerSelectionController, with two actions: 我的Rails应用程序只有一个CustomerSelectionController,其中有两个操作:
index: which shows a form where the user can enter customer information and select: which just displays a static page. index:显示一个表单,用户可以在其中输入客户信息,然后选择:仅显示一个静态页面。
class CustomerSelectionController < ApplicationController
def index
end
def select
end
end
I've created an entry in my routes.rb file: 我在routes.rb文件中创建了一个条目:
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 找不到CustomerSelectionController的“显示”操作
I'm not sure why it is trying to perform an action called show? 我不确定为什么要尝试执行名为show的操作? I haven't defined or referenced one anywhere.
我没有在任何地方定义或引用一个。
I'm not sure why it is trying to perform an action called show?
我不确定为什么要尝试执行名为show的操作? I haven't defined or referenced one anywhere.
我没有在任何地方定义或引用一个。
Yes you have. 是的,你有。 That's what
resources
does. 这就是
resources
作用。 It defines the seven default RESTful routes: index, show, new, create, edit, update and destroy. 它定义了七个默认的RESTful路由:索引,显示,新建,创建,编辑,更新和销毁。 When you route to
/customer_selection/select
, the route that matches is "/customer_action/:id", or the "show" route. 当您路由到
/customer_selection/select
,匹配的路由是“ / customer_action /:id”或“ show”路由。 Rails instantiates your controller and attempts to invoke the "show" action on it, passing in an ID of "select". Rails实例化您的控制器,并尝试在其上调用ID号为“ select”的“ show”操作。
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
: 由于路线很少,因此您也可以不使用
resources
就可以定义它们:
get "/customer_selection" => "customer_selection#index"
get "/customer_select/select"
Note that, in the second route, the "customer_select#select"
is implied. 注意,在第二条路径中,暗含
"customer_select#select"
。 In a route with only two segments, Rails will default to "/:controller/:action" if you don't specify a controller/action. 在只有两个网段的路由中,如果您未指定控制器/动作,Rails将默认为“ /:controller /:action”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.