I have this controller:
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
I'm passing a test to see if everything will be correct when it comes to the controllers. The test is as follows:
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
When I pass this test a strange error happens, it seems that in the controller it is not able to get the id when I indicate in the to redirect to the show route. The error is:
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]
It's missing the salesman's id, I did not understand why and I do not know how to get out of this situation.
My routes are:
Rails.application.routes.draw do
resources :companies do
resources :salesmen
resources :goals do
resources :days
end
end
devise_for :owners, :controllers => { registrations: 'registrations' }
end