Ruby on rails 找不到没有id的用户?
我的产品和用户表出现此错误 --找不到没有id的用户Ruby on rails 找不到没有id的用户?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我的产品和用户表出现此错误 --找不到没有id的用户 def set_user @user = User.find(params[:user_id]) end 我已经像这样嵌套了这些路线 resources :users do resources :products do resources :reviews end end 这是我的产品控制器 class ProductsController < ApplicationController
def set_user
@user = User.find(params[:user_id])
end
我已经像这样嵌套了这些路线
resources :users do
resources :products do
resources :reviews
end
end
这是我的产品控制器
class ProductsController < ApplicationController
before_action :require_signin, except: [:index, :show]
before_action :set_user
def index
@products = @user.products
end
def show
@product = Product.find(params[:id])
end
def edit
@product = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
if @product.update(product_params)
redirect_to [@user, @product], notice: "Product successfully updated!"
else
render :edit
end
end
def new
@product = @user.products.new
end
def create
@product = @user.products.new(product_params)
@product.user = current_user
if @product.save
redirect_to user_products_path(@product, @user), notice: "Product successfully created!"
else
render :new
end
end
def destroy
@product = Product.find(params[:id])
@product.destroy
redirect_to user_products_path(@product, @user), alert: "Product successfully deleted!"
end
private
def product_params
params.require(:product).permit(:title, :description, :posted_on, :price, :location, :category)
end
def set_user
@user = User.find(params[:user_id])
end
end
class ProductsController
我所要做的就是把用户和产品联系起来,这样产品就属于用户,用户有很多产品
class Product < ActiveRecord::Base
belongs_to :user
has_many :reviews
class User < ActiveRecord::Base
has_secure_password
has_many :reviews, dependent: :destroy
has_many :products, dependent: :destroy
类产品
对于控制器的任何操作,您应该传递用户id参数。
错误的原因是params[:user_id]等于nil,因为其他用户提到params[:user_id]值可能为零 也就是说,您似乎已经在控制器的作用域中定义了一个当前用户。我看到它在创建操作中被引用。我敢打赌,这是在行动前要求登录设置的。考虑到我认为您正在尝试做的事情,这可能会使您的set_user before_操作有点多余 您可以在当前使用@user的任何位置引用控制器中的当前用户。或者,您可以在设置用户之前的设置用户中设置@user=current\u user 旁注: 仔细查看您的创建操作:
def create
@product = @user.products.new(product_params)
@product.user = current_user
if @product.save
redirect_to user_products_path(@product, @user), notice: "Product successfully created!"
else
render :new
end
end
如果我错了,请纠正我,但我相信执行@model.association.new之类的操作会为新创建的关联对象设置model\u id,因此我会更改这两行
@product = @user.products.new(product_params)
@product.user = current_user
简单地说
@product = current_user.products.new(product_params)