在我看来,我有下一个:
form_for([@product, @product.comments.create(user_id: session[:user_id],product_id: @product.id)],remote: true)
comments_controller:
def create
@product = Product.find(params[:product_id])
@comment = @product.comments.create(comment_params)
respond_to do |format|
if @comment.save
@user = User.find(@comment.user_id)
format.js {}
else
format.js { flash.now[:notice] = @comment.errors.full_messages.to_sentence }
end
end
end
private
def comment_params
params.require(:comment).permit(:body, :product_id, :user_id)
end
但是如果尝试提交评论,我会收到错误,例如用户不能为空,为什么params来自创建不通过?
答案 0 :(得分:1)
请改为尝试:
form_for([@product, @product.comments.build], remote: true)
comments_controller:
def create
@product = Product.find(params[:product_id])
@comment = @product.comments.build(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.js {}
else
format.js { flash.now[:notice] = @comment.errors.full_messages.to_sentence }
end
end
end
private
def comment_params
params.require(:comment).permit(:body)
end
有几个缺陷:
current_user
,所以使用它