请有人留下一些关于如何使用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
预期结果将是发表评论而没有任何错误
答案 0 :(得分:0)
如果您要创建一个处理多种类型的可注释类型的控制器,则可以检查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