【问题标题】:How to post with friendly_id in Rails?如何在 Rails 中使用friendly_id 发帖?
【发布时间】:2019-01-27 23:15:13
【问题描述】:

有人可以提供有关如何使用friendly_id 发帖的提示吗?

在设置了一个简单的评论系统后,没问题,但是使用friednly_id,我尝试在日志中发布评论轨

Completed 422 Unprocessable Entity in 241ms 

似乎是因为没有将正确的 id 传递给参数

 Parameters: {"comment"=>{"commentable_id"=>"dde", "comment"=>"swsww", "commentable_type"=>"Post", "parent_id"=>"", "post_id"=>"dde"}, "post_id"=>"dde"}

更多相关信息:

我尝试过直接使用帖子而不是资源,但还是一样

set_commentable
@commentable = if params[:comment_id]
                   Comment.find_by_id(params[:comment_id])
                 elsif params[:post_id]
                   Post.friendly.find(params[:post_id])
                 end
end

 def set_comment
    @comment = @commentable.comments.friendly.find(params[:id])
  rescue StandardError => e
    logger.error "#{e.class.name} : #{e.message}"
    @comment = @commentable.comments.build
    @comment.errors.add(:base, :recordnotfound, message: "That record doesn't exist. Maybe, it is already destroyed.")
  end

  def set_commentable
    resource, id = request.path.split('/')[1, 2]

    @commentable = resource.singularize.classify.constantize.friendly.find(id)
  end

  def set_post
    @post = Post.friendly.find(params[:post_id] || params[:id])
  end

预期的结果将是发表评论没有任何错误

stacktrace

【问题讨论】:

  • 如果您添加有关错误堆栈跟踪的更多信息会更好。
  • @SebastianPalma,谢谢我添加了错误图片
  • rails console试试吧。

标签: javascript ruby-on-rails ruby reactjs


【解决方案1】:

如果您想创建一个控制器来处理多种类型的可注释类型,您可以检查 params 哈希是否存在嵌套键:

class CommentsController
  before_action :set_commentable

  private

  def set_commentable
    raise ActiveRecord::RecordNotFound unless commmentable_key
    @commentable = commentable_class.includes(:comments)
                                    .friendly.find(params[commmentable_key])
  end

  def commmentable_key
     @_commmentable_param ||= ["post_id", "video_id"].detect { |key| params[key].present? }
  end

  def commentable_class
    commmentable_key.chomp("_id").classify.constantize
  end
end

在本例中,我们检查键“post_id”和“video_id”。然后,我们使用一组简单的启发式方法来猜测该类是 Post 还是 Video。

通过将其提取到单独的方法中,您可以覆盖子类中的行为。

如果没有找到记录,不要使用rescue StandardError => e 来捕获发生的错误。它是一种称为pokémon exception handling 的反模式。只捕获您知道如何处理的特定异常。

 # DON'T DO THIS!
 rescue StandardError => e
    logger.error "#{e.class.name} : #{e.message}"
    @comment = @commentable.comments.build
    @comment.errors.add(:base, :recordnotfound, message: "That record doesn't exist. Maybe, it is already destroyed.")
  end

如果您想覆盖 rails 中的默认 404 处理程序,请改用 rescue_from 来拯救 ActiveRecord::RecordNotFound。这将退出控制器中的操作,这是一件好事,因为它不必处理资源不存在的情况。

class CommentsController
  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  def not_found
    render :not_found, status: :not_found
  end
end

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2016-10-06
    • 1970-01-01
    • 2015-02-12
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多