Reputation: 112
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 :
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?
Upvotes: 0
Views: 71
Reputation: 115541
Try this instead:
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
There were several flaws:
current_user
, so use itUpvotes: 1