2015-05-11 39 views
0

在我看來,我有未來:Rails的params爲不及格

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

試試這個:

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 

有幾個缺陷:

  • 你每一個頁面被刷新
  • 時創建評論210
  • 你不應該依賴params用於在當前用戶ID,你有current_user,所以用它
  • 相同產品:你擁有它,因爲它的嵌套,所以不要依靠附加PARAM