Rails路由重定向到错误的路径

时间:2012-06-18 00:03:12

标签: ruby-on-rails-3 forms routes

我有一个名为“clients”的视图,它显示来自Call数据库的调用列表。这很好。但是,当我添加一个带有表单后面的新按钮时,将会创建一个调用,但它会重定向到calls_path而不是clients_path。

我不知道为什么会这样做,我唯一的理论是我正在处理触及clients_controller之外的数据的操作,并且不知何故Rails默认为calls_path。我的删除操作也发生了同样的事情。有人能帮助我理解这个吗?

calls_controller
def new
    @call = Call.new :call_status => "open"

    respond_with @call
  end

  def create
    @call = Call.new(params[:call])

     if @call.save
        redirect_to clients_path, notice: "Call was successfully created."
      else
        render :new
     end
  end 

  def destroy
      @call = Call.find(params[:id])
      @call.destroy

      respond_to do |format|
        format.html { redirect_to clients_index_path }
        format.json { head :no_content }
      end
    end

_form.html.erb
<%= form_for(@call) do |f| %>

  <%= f.label :caller_name %>
  <%= f.text_field :caller_name %>
  <%= f.label :caller_phone %>
  <%= f.text_field :caller_phone, :placeholder => 'xxx-xxx-xxxx' %>
  <%= f.label :caller_email %>
  <%= f.text_field :caller_email %>

  <%= f.button :submit %>

<% end %>

routes.rb
devise_for :users
  match 'mdt' => 'mdt#index'
  get "home/index"
  resources :medics
  resources :clients
  resources :users
  resources :units
  resources :mdt do
    collection do
      put "in_service"
      put "en_route"
      put "to_hospital"
      put "at_hospital"
      put "on_scene" 
      put "out_of_service" 
      put "at_station"
      put "staging"
      put "at_post"
      put "man_down"
  end
  end
  resources :calls do
    member do
      post 'close'
    end
  end
  root :to => 'home#index'
  devise_scope :user do
    get "/login" => "devise/sessions#new"
    delete "/logout" => "devise/sessions#destroy"
  end

1 个答案:

答案 0 :(得分:0)

我遇到的问题是路线问题。我需要一个新方法的post方法。创建两个动作(一个用于创建,一个用于销毁)以及它们的路由后,一切都开始工作。看起来它似乎正在尝试使用默认路由和操作,这些路由和操作会为我的目的重新路由到错误的URL。

resources :clients do
    collection do
      post "calls"
    end
    member do
      delete "cancel"
    end
  end



 def calls
    @call = Call.new(params[:call])

     if @call.save
        redirect_to clients_path, notice: "Call was successfully created."
      else
        render :new
     end
  end 

  def cancel
      @call = Call.find(params[:id])
      @call.destroy

      respond_to do |format|
        format.html { redirect_to clients_path }
        format.json { head :no_content }
      end
    end