关于这个主题有很多回答的问题,但我似乎无法应用我的问题的答案。我收到以下错误:
ItemsController POST create redirect to show page
Failure/Error: @user = User.find(params[:user_id])
ActiveRecord::RecordNotFound:
Couldn't find User with 'id'=
我知道错误的原因是因为user_id是nil但我似乎无法弄清楚原因。我仍然是Rails的新手,请原谅我,如果这是一个非常简单的解决方案。
RSpec测试
require 'rails_helper'
RSpec.describe ItemsController, type: :controller do
describe "POST create" do
it "redirect to show page" do
post :create, user_id: @user, item: { name: "name"}
expect(response).to redirect_to(user_show_path)
end
end
end
项目控制器
class ItemsController < ApplicationController
def create
@user = User.find(params[:user_id])
@item = Item.new(item_params)
@item.user = current_user
if @item.save
@item = Item.update_items(params[:items])
redirect_to current_user, notice: "Item was saved successfully."
else
flash[:error] = "Error creating item. Please try again."
render user_show_path
end
end
private
def item_params
params.require(:item).permit(:name)
end
end
路线
user_items POST /users/:user_id/items(.:format) items#create
...我已经为用户部分实施了设计。在此先感谢您的帮助!
答案 0 :(得分:1)
您需要在使用之前创建@user。您可以使用factory_girl gem或直接执行
@user = User.create
post :create, user_id: @user.id, item: { name: "name"}
希望这有效