【问题标题】:How do I create a rails controller action?如何创建 Rails 控制器操作?
【发布时间】:2013-02-12 17:56:48
【问题描述】:

我的 rails 应用有一个 CustomerSelectionController,有两个操作:

index:显示一个表单,用户可以在其中输入客户信息和 select: 只显示一个静态页面。

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 的操作?我没有在任何地方定义或引用过。

【问题讨论】:

标签: ruby-on-rails action


【解决方案1】:

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

是的,你有。这就是resources 所做的。它定义了七个默认的 RESTful 路由:索引、显示、新建、创建、编辑、更新和销毁。当您路由到/customer_selection/select 时,匹配的路由是“/customer_action/:id”或“show”路由。 Rails 实例化您的控制器并尝试对其调用“显示”操作,并传入“选择”的 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”。

【讨论】:

  • 我可以直接删除资源行,让约定优于配置吗?
  • 不,你仍然需要定义一个路由。不过,您没有有使用resources,请参阅我的更新答案。
  • 好的,我在哪里可以得到该代码块的简明解释?
  • 酷,我更喜欢你的第二个选项。我可以阅读它。谢谢。
  • Rails 路由指南,在 cmets 中链接到您的问题:guides.rubyonrails.org/routing.html
猜你喜欢
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2011-06-23
  • 2015-01-01
相关资源
最近更新 更多