nikolay
nikolay

Reputation: 112

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 :

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

Answers (1)

apneadiving
apneadiving

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:

  • you created a comment each time the page was refreshed
  • you should not rely on params for current user id, you have the current_user, so use it
  • same for product: you have it since its nested, so dont rely on the additional param

Upvotes: 1

Related Questions