current_user和销毁评论(精炼)

时间:2015-02-12 19:01:58

标签: ruby-on-rails associations destroy

我最近发布了一个与此类似的问题,但我已经缩小了问题范围,并希望改进这个问题。无论如何,我有一个博客与食谱(相当于帖子或文章)和这些食谱的评论。我在application_controller.rb文件中输入了current_user的代码:

def current_user
  return unless session[:user_id]
  @current_user = User.find_by_id(session[:user_id])
end

# Make current_user available in templates as a helper
helper_method :current_user

我尝试将其设置为必须登录才能删除对文章的评论。该代码位于我的comments_controller.rb文件中:

def destroy
  @recipe = current_user.recipes.find(params[:recipe_id])
  @comment = @recipe.comments.find(params[:id])
  @comment.destroy
  redirect_to @recipe, notice: 'Comment Deleted'
end

我已将其缩小到destroy方法中的第一行代码。我相信我的应用程序无法将配方与current_user相关联,因此无法正确保存@recipe,因此@comment不会删除。当我尝试使用登录用户删除评论时,每个食谱都有一个user_id参数,这是来自服务器控制台的错误:

Started DELETE "/recipes/4/comments/4" for 127.0.0.1 at 2015-02-12 13:42:54 -0500

Processing by CommentsController#destroy as HTML
Parameters: {"authenticity_token"=>"+0pWfNOPJXLOzgUhA//q4ySh5rk01SlKmTRQx0qdDOrvkUOcIzF8GCb5jKwjsDlUvQsxxGTOOtJv6rPjn3jfoA==", "recipe_id"=>"4", "id"=>"4"}

User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 6]]
CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 6]]

Recipe Load (0.1ms)  SELECT  "recipes".* FROM "recipes" WHERE "recipes"."user_id" = ? AND "recipes"."id" = ?  ORDER BY published_at DESC, title ASC LIMIT 1  [["user_id", 6], ["id", 4]]

Completed 404 Not Found in 50ms

ActiveRecord::RecordNotFound (Couldn't find Recipe with 'id'=4 [WHERE "recipes"."user_id" = ?]):
app/controllers/comments_controller.rb:15:in `destroy'

有人有什么想法吗?

注意:当我将comments_controller的destroy方法中的第一行代码更改为:

@recipe = Recipe.find(params[:recipe_id])

它有效。虽然bc然后未登录的用户可以删除评论,但我不希望它成为代码。并且,修改后的代码与我在comments_controller中的私有方法代码相同:

private
def load_recipe
  @recipe = Recipe.find(params[:recipe_id])
end

我的comments_controller中还有一个关于该方法的before_filter:

before_filter :load_recipe, :except => :destroy
before_filter :authenticate, :only => :destroy

0 个答案:

没有答案