[英]How do I create another controller action to create an object in rails?
[英]How do I create a rails controller action?
我的Rails应用程序只有一个CustomerSelectionController,其中有两个操作:
index:显示一个表单,用户可以在其中输入客户信息,然后选择:仅显示一个静态页面。
class CustomerSelectionController < ApplicationController
def index
end
def select
end
end
我在routes.rb文件中创建了一个条目:
resources :customer_selection
索引视图中的表单如下所示:
<h1>Customer Selection</h1>
<%= form_tag("customer_selection/select", :method => "get") do %>
<%= submit_tag("Select") %>
<% end %>
但是,当我单击浏览器中的“选择”按钮时,我得到的只是:
未知动作
找不到CustomerSelectionController的“显示”操作
我不确定为什么要尝试执行名为show的操作? 我没有在任何地方定义或引用一个。
我不确定为什么要尝试执行名为show的操作? 我没有在任何地方定义或引用一个。
是的,你有。 这就是resources
作用。 它定义了七个默认的RESTful路由:索引,显示,新建,创建,编辑,更新和销毁。 当您路由到/customer_selection/select
,匹配的路由是“ / customer_action /:id”或“ show”路由。 Rails实例化您的控制器,并尝试在其上调用ID号为“ select”的“ show”操作。
如果除了这些路由之外,还想添加一条路由,则需要明确定义它,并且如果不想全部使用七个路由,还应该明确声明要使用的路由:
resources :customer_selection, only: %w(index) do
collection { get :select }
# or
# get :select, on: :collection
end
由于路线很少,因此您也可以不使用resources
就可以定义它们:
get "/customer_selection" => "customer_selection#index"
get "/customer_select/select"
注意,在第二条路径中,暗含"customer_select#select"
。 在只有两个网段的路由中,如果您未指定控制器/动作,Rails将默认为“ /:controller /:action”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.