Как найти find_by_id при использовании friendly_id (для полиморфных отношений) - PullRequest
0 голосов
/ 30 июня 2018

Как мне разрешить работать find_by_id, чтобы мои комментарии работали с моими сообщениями, в которых есть слагы через friendly_id? Есть ли альтернативный подход к этому?

Я установил гем Ruby с именем friendly_id и использую его для создания slugs в своих сообщениях в блоге. Эти сообщения в блоге имеют комментарии через polymorphic отношения. У меня есть эти противоречивые методы, которые я считаю причиной, по которой мои комментарии не работают, и выдает ошибку:

undefined method 'comments' for nil:NilClass

Указывает на @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 голосов
/ 30 июня 2018

В соответствии с документами вам нужно запросить модели Comment и Post немного по-другому, так как посты имеют 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
...