【问题标题】:Rails 4 form_tag submitting to wrong controller actionRails 4 form_tag提交到错误的控制器动作
【发布时间】:2015-10-16 02:29:52
【问题描述】:

这感觉很愚蠢,但到目前为止,我所阅读的所有内容都让我觉得我做得对,但它仍然不起作用。

我正在使用 form_tag 将参数提交给自定义控制器操作。而不是我指出的动作,它似乎打算提交到我的控制器中的show 动作,我需要为配置文件保留它。无论如何,这是代码(请原谅它是未重构的状态):

医生控制器:

class DoctorsController < ApplicationController
  def new
  end

  def show
    @doctor_list = Doctor.find(params[:id])
  end

  def index
    @doctor_list = Doctor.all
  end

  def search
  end

  def results
    if params[:zip] && params[:zip].length === 5 && params[:zip]
      @doctor_list = Doctor.where("zip = ?", params[:zip])
    elsif params[:id]
      begin
        @doctor_list = []
        @doctor_list<<Doctor.find(params[:id])
      rescue
        flash.now[:errors] = "That doctor does not exist!"
        render 'search'
      end
    else
      flash.now[:errors] = "That is not a valid zipcode!"
      render 'search'
    end
  end
end

路线:

  resources :users
  resources :doctors

  root 'doctors#search'
  get 'doctors/results' => 'doctors#results'

search.html.erb:

<% provide(:title, "Home") %>

<div class="hero">
  <h1>Find an M.D.</h1>

  <%= form_tag(doctors_results_path, method: "get") do %>
    <%= label_tag("Zipcode: ") %>
    <%= text_field_tag(:zip) %><br>

    <%= submit_tag "FIND", class: "button"%>
  <% end %>
</div>

同样,问题是我收到错误 (Couldn't find Doctor with 'id'=results),因为表单使用的是我的显示操作与我的结果操作。应用程序跟踪显示错误位于app/controllers/doctors_controller.rb:6:in 'show'。作为一个额外的混淆,我不真的理解为什么它在提交时发送"id"=&gt;"results"作为参数哈希的一部分,但如果它使用正确的,这似乎不是问题控制器动作开始。

感谢您的任何想法。

【问题讨论】:

  • 尝试将get 'doctors/results' =&gt; 'doctors#results'移到resources :doctors上方
  • @Pavan 呃,就是这样。只是一个优先问题?由于 resources :doctors 是第一位的,所以它优先考虑这一点(以及表演动作),而不是我告诉它的?

标签: forms ruby-on-rails-4 controller routing ruby-2.0


【解决方案1】:

是的,这是一个优先问题。由于resources :doctors 是第一位的,所以GET show 的优先级将高于get 'doctors/results' =&gt; 'doctors#results'

将'doctors/results' =&gt; 'doctors#results' 移到resources :doctors 上方应该可以解决您的问题

#routes.rb
root 'doctors#search'
get 'doctors/results' => 'doctors#results'

resources :users
resources :doctors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2011-06-18
    • 2016-11-16
    相关资源
    最近更新 更多