没有路由匹配{:行动=>“节目”,:控制器=>“用户”,:ID =>零}(No r

2019-09-19 17:23发布

大家好,我有这个问题(后标题)。

Failure/Error: get :create, :user => { :email => 'foo@example.com', :name => 'userexample' }
ActionController::RoutingError:No route matches {:action=>"show", :controller=>"user", :id=>nil}

这是我的UserController

class UserController < ApplicationController

  def new
  end

  def create
    @user = User.new(params[:user])
    @user.save
    redirect_to :action => :show, :id => @user.id
  end

  def show
    @user = User.find(params[:id])
  end
end

这里是我的routes.rb

::Application.routes.draw do

  devise_for :users
  root :to => "user#index"
  resources :user
  #match "newuser" => "user#new"
  get "user/new"
  post "user/create"
  get "user/:id" => "user#show"

这里是我的RSpec的测试

require 'spec/spec_helper'

describe UserController do
  it "create new user" do
    get :create, :user => { :email => 'foo@example.com', :name => 'userexample' }
      flash[:notice] = 'new user was successfully created.'
    end
  end
end

Answer 1:

if @user.save
   redirect_to :action => :show, :id => @user.id
else
 ...
end


Answer 2:

大多数Rails应用使用这种类型的内容块的创建和更新记录。

def create
  @user = User.new(params[:user])

  if @user.save
    redirect_to @user, :notice => "User was created successfully."
  else
    render :new
  end
end

基本上,当create操作时,它会创建一个新的记录,或一个新实例User模型。

.save被称为它会检查所有的验证。 如果验证通过,则返回true,否则返回false。

如果返回false,那么你需要渲染:new再次模板,这样的人有机会修复任何验证错误。

如果返回true,那么你要重定向到show动作。 关于轨道很酷的事情是, 它可以自动找出答案被正好路过的实例@user


瑞安贝茨有一个教程使用RSpec测试控制器 。 基于他做什么,这是我怎么会测试你的控制器。

require 'spec/spec_helper'

describe UserController do

  describe "POST 'create'" do

    it "should redirect to user on successful save" do
      User.any_instance.stub(:valid?) { true }
      post :user
      flash[:notice].should_not be_nil
      assigns(:user).should_not be_a_new_record
      response.should redirect_to(assigns(:user))
    end

    it "should render new template on failed save" do
      User.any_instance.stub(:valid?) { false }
      post :user
      flash[:notice].should be_nil
      assigns(:user).should be_a_new_record
      response.should render_template(:new)
    end

    it "should pass params" do
      User.any_instance.stub(:valid?) { true }
      post :user, :user => { email_address: "baylor@example.com" }
      assigns(:user).email_address.should == "baylor@example.com"
    end
  end
end


文章来源: No route matches {:action=>“show”, :controller=>“user”, :id=>nil}