Rails params没有通过

时间:2015-05-11 07:20:20

标签: ruby-on-rails

在我看来,我有下一个:

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来自创建不通过?

1 个答案:

答案 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

有几个缺陷:

  • 您每次刷新页面时都创建了一条评论
  • 你不应该依赖params获取当前用户ID,你有current_user,所以使用它
  • 同样的产品:你拥有它,因为它嵌套,所以不要依赖额外的参数
相关问题