简体   繁体   English

Rails参数没有过去

[英]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: 有几个缺陷:

  • 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 您不应该依赖于params作为当前用户ID,而是使用current_user ,因此请使用它
  • same for product: you have it since its nested, so dont rely on the additional param 产品同样如此:您自嵌套以来就拥有它,因此不要依赖其他参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM