Rails 4 form_tag提交错误的控制器操作

时间:2015-07-25 13:43:03

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

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

我正在使用form_tag将params提交给自定义控制器操作。而不是我指示的操作,它似乎意图提交到我的控制器中的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),因为表单正在使用我的show action与结果操作。应用程序跟踪表明错误位于app/controllers/doctors_controller.rb:6:in 'show'。作为一个额外的混乱,我不真的理解为什么它在提交时发送"id"=>"results"作为params散列的一部分,但是如果它会使用它似乎可能是一个非问题正确的控制器动作开始。

感谢您的任何想法。

1 个答案:

答案 0 :(得分:3)

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

'doctors/results' => 'doctors#results'移到resources :doctors之上可以解决您的问题

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

resources :users
resources :doctors