[英]Rails params is not passing
In my view I have next : 我认为下一步是:
form_for([@product, @product.comments.create(user_id: session[:user_id],product_id: @product.id)],remote: true)
comments_controller : 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
But if try to submit comment, I get error like user cant be blank, why params from create not passing? 但是,如果尝试提交评论,则会收到类似用户不能为空的错误,为什么创建的参数没有通过?
Try this instead: 尝试以下方法:
form_for([@product, @product.comments.build], remote: true)
comments_controller : 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
There were several flaws: 有几个缺陷:
current_user
, so use it current_user
,因此请使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.