簡體   English   中英

如何創建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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM