控制器找不到要重定向到的ID

时间:2017-10-29 13:18:59

标签: ruby-on-rails rspec

我有这个控制器:

class SalesmenController < ApplicationController
  before_action :find_salesman, only: [:show]


  def show
    authorize! :read, @salesman
  end

  def create
    @salesman = Salesman.new(params_salesman)
    authorize! :create, @salesman
    if @salesman.save
      flash[:notice] = "Salesman saved!"
      redirect_to company_salesman_path(@salesman.id)
    else
      flash.now[:error] = "Cannot create salesman!"
      render :new
    end
  end

private
  def params_salesman
    params.require(:salesman).permit(:name, :company_id)
  end

  def find_salesman
    @salesman = Salesman.find(params[:id])
  end
end

我通过测试,看看控制器是否一切正确。测试如下:

require 'rails_helper'

RSpec.describe SalesmenController, type: :controller do
   include Devise::Test::ControllerHelpers

   before(:each) do
    @request.env["devise.mapping"] = Devise.mappings[:owner]
    @current_owner = FactoryGirl.create(:owner)
    sign_in @current_owner
    @current_company = FactoryGirl.create(:company, owner: @current_owner)
  end

describe "POST #create" do
    before(:each) do
      salesman = FactoryGirl.create(:salesman, company: @current_company)
      post :create, params: {:company_id => @current_company.id, salesman: { name: salesman.name, company_id: @current_company.id } }
    end

    it "redirect to new team" do
      expect(response).to have_http_status(:success)
    end

    it "Create team with right attributes" do
      expect(Salesman.last.company).to eql(@current_company)
      expect(Salesman.last.name).to eql(@salesman[:name])
    end
  end
end

当我通过此测试时会发生一个奇怪的错误,似乎在控制器中,当我指示重定向到show route时,它无法获取id。错误是:

 1) SalesmenController POST #create redirect to new team
     Failure/Error: redirect_to company_salesman_path(@salesman.id)

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :company_id=>390, :controller=>"salesmen"} missing required keys: [:id]

它错过了推销员的身份,我不明白为什么,我不知道如何摆脱这种情况。

我的路线是:

Rails.application.routes.draw do
  resources :companies do
    resources :salesmen
    resources :goals do
      resources :days
    end
  end
  devise_for :owners, :controllers => { registrations: 'registrations' }
end

1 个答案:

答案 0 :(得分:0)

尝试

redirect_to company_salesman_path(:id => @salesman.id)

redirect_to company_salesman_path(@salesman)
希望这会有所帮助。