使用friendly_id时如何查找find_by_id(用于多态关系)

时间:2018-06-30 13:35:51

标签: ruby-on-rails ruby slug friendly-id

  

我如何允许find_by_id起作用,以便我的评论可以与通过friendly_id出现滞后的帖子一起使用?有替代的方法吗?

我已经安装了名为friendly_id的Ruby gem,并用它在我的博客文章中创建slugs。这些博客帖子通过polymorphic关系具有评论。我有以下我认为 冲突的方法,这是我的评论无法正常工作并引起错误的原因:

undefined method 'comments' for nil:NilClass

评论控制器中的 create方法中指向@comment = @commentable.comments.new comment_params

在我的评论模型中:

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  has_many :comments, as: :commentable, dependent: :destroy
end

在我的评论控制器中:

class CommentsController < ApplicationController
  before_action :find_commentable

  def new
    @comment = Comment.new
  end

  def create
    @comment = @commentable.comments.new comment_params
    if @comment.save
      flash[:success] = "Thanks for sharing your thoughts!"
      redirect_back fallback_location: root_path
    else
      flash[:danger] = "There was an error posting your comment!"
      redirect_back fallback_location: root_path
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:body, :email, :name)
  end

  def find_commentable
    @commentable = Comment.find_by_id(params[:comment_id]) if params[:comment_id]
    @commentable = Post.find_by_id(params[:post_id]) if params[:post_id]
  end
end

在我的帖子模型中: has_many :comments, as: :commentable

我的路线:

resources :comments do
  resources :comments
end

我的服务器日志:

app/controllers/comments_controller.rb:9:in `create'
Started POST "/posts/top-5-audio-industry-blogs/comments" for 127.0.0.1 at 2018-06-30 10:35:09 -0300
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[token]", "comment"=>{"body"=>"Hey, thanks for checking out the article! Any questions? Just ask me here and I'll be happy to help.", "name"=>"name", "email"=>"email", "nickname"=>""}, "commit"=>"Post Comment", "post_id"=>"top-5-audio-industry-blogs"}
Post Load (0.0ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = $1 ORDER BY "posts"."created_at" DESC LIMIT $2  [["id", 0], ["LIMIT", 1]]
Completed 500 Internal Server Error in 27ms (ActiveRecord: 6.0ms)



NoMethodError (undefined method `comment' for nil:NilClass):

我唯一能想到的就是此错误的原因,因为它不会产生任何故障。感谢您的任何事先帮助!

1 个答案:

答案 0 :(得分:2)

根据docs,您需要查询CommentPost模型稍有不同,因为帖子包含slugs,而注释则没有。见下文:

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

  # You should also handle the case if `@commentable` is `nil` after above.
  redirect_to somewhere, error: 'Post/Comment not found' unless @commentable
end