【问题标题】:Rails form going to create action instead of index actionRails 表单将创建操作而不是索引操作
【发布时间】:2018-05-23 19:56:02
【问题描述】:

我正在尝试创建一个搜索表单,它将获取结果并将参数推送到搜索控制器的索引中。但是,即使我在表单中指定了 get 方法,我仍然收到错误 The action 'create' could not be found for SearchController,即使我正在尝试加载索引。

home/index.html.erb

<%= form_tag(controller: "search", :url => search_index_path, :method 
=> :get) do %>
<%= label_tag(:name, "Search for:") %>
<%= text_field_tag(:name) %>
<%= submit_tag("Search") %>
<% end %>

search_controller.rb

class SearchController < ApplicationController
  def index
    @search = Tmdb::Search.tv(params[:name])
  end
  def show
  end
end

routes.rb

Rails.application.routes.draw do
 root 'home#index'
 resources :home
 resources :search
end

表单输出:

<form action="/search?method=get" accept-charset="UTF-8" method="post" abineguid="2F75F785E35A4ED5B614E26762C7B53B"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="6dKa4a+vBvybu9b4eYwuEqx9dNcvadCyqRz7ox+ggW2YVAWq6Y8BWVNHx8nDWJbnQ4hTl5OTi3TSkjUfFuHbCQ==">
<label for="name">Search for:</label>
<input type="text" name="name" id="name">
<input type="submit" name="commit" value="Search" data-disable-with="Search">
</form>

感谢您的帮助!

【问题讨论】:

  • 在您的网络浏览器中检查您的输出页面,然后发布form_tag 生成的&lt;form&gt; 标签。
  • @Phlip 我添加了表单输出。

标签: ruby-on-rails


【解决方案1】:

您对 form_tag 的调用是错误的。

form_tag(url_for_options = {}, options = {}, &block)

您将所有选项传递给 url_for_options,包括 :method。 你应该这样做:

<%= form_tag({ controller: "search", action: "index" }, { :method 
=> :get }) do %>

或者更简单:

<%= form_tag(search_index_path, :method => :get) do %>
<%= label_tag(:name, "Search for:") %>
<%= text_field_tag(:name) %>
<%= submit_tag("Search") %>
<% end %>

见:https://apidock.com/rails/ActionView/Helpers/FormTagHelper/form_tag

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多