如何创建rails控制器操作?

时间:2013-02-12 17:56:49

标签: ruby-on-rails 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的操作?我没有在任何地方定义或引用它。

1 个答案:

答案 0 :(得分:1)

  

我不确定为什么要尝试执行名为show的操作?我没有在任何地方定义或引用它。

是的,你有。这就是resources的作用。它定义了七个默认的RESTful路由:索引,显示,新建,创建,编辑,更新和销毁。当您路由到/customer_selection/select时,匹配的路由是“/ customer_action /:id”或“show”路由。 Rails实例化你的控制器并试图在其上调用“show”动作,传入一个“select”ID。

如果你想要添加除了那些之外的路线,你需要明确地定义它,如果你不想要全部七个,你还应该明确说明你想要的路线:

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”。

相关问题