Как исправить ошибку Rails.ajax в консоли сайта? - PullRequest
0 голосов
/ 29 декабря 2018

У меня есть 2 разных типа постов (новости и статьи).Когда я иду в новости и пытаюсь комментировать любые новости, ничего не происходит.В консоли Google Chrome написано:

POST /news/artifact-v-spiske-liderov-prodazh-steam-po-itogam-2018-goda/comments/ 404
rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:7 
Rails.ajax @ rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:7
Rails.handleRemote @ rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:31
(anonymous) @ rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:5

НО!Когда я пытаюсь комментировать в типе статей, все хорошо, комментарии работают.В чем проблема?

Мой _form.html.haml:

- if user_signed_in? && current_user.mute_to && current_user.mute_to > Time.current
%div
%strong
  = "Вы не можете писать комментарии до #{current_user.mute_to.strftime("%F %R")}"
- elsif user_signed_in?
= form_with model: [commentable, Comment.new], html: { class: 
local_assigns[:class], data: { target: local_assigns[:target] } } do |form|
.form-group
  = form.text_area :body, placeholder: "Напишите комментарий (минимум 3 символа)", class: "form-control"
.form-group
  = form.hidden_field :parent_id, value: local_assigns[:parent_id]
  = form.submit 'Отправить', class: "btn"

Мой _comment.html.haml:

- nesting     = local_assigns.fetch(:nesting, 1)
- max_nesting = local_assigns[:max_nesting]
- continue_thread = local_assigns[:continue_thread]
= tag.div id: dom_id(comment), class: "border-left pl-4 my-4" do
- if comment.deleted?
%strong [комментарий удален]
%small
  = link_to time_ago_in_words(comment.created_at), url_for(comment: comment.id, anchor: dom_id(comment))
%p [комментарий удален]
- else
- comments_user = comment.user
%strong.comments_user_line
  = fa_icon "user-circle", class: "mr-1"
  = link_to comments_user.nickname, user_path(comments_user), class: 'user_link'
%small
  = link_to time_ago_in_words(comment.created_at), polymorphic_path(comment.commentable, comment: comment.id, anchor: dom_id(comment))
= simple_format comment.body
%div.comments_block
- if user_signed_in? && current_user.mute_to && current_user.mute_to > Time.current
- else
  %small
    - if user_signed_in? 
      %btn.reply Отвеить
    - else
      = link_to "Отвеить", new_user_session_path
    = link_to "Удалить", [comment.commentable, comment], method: :delete, data: {confirm: "Вы уверены?"} if comment.user == current_user
  = render partial: "comments/form", locals: {                       |
      commentable: comment.commentable,                              |
      parent_id: reply_to_comment_id(comment, nesting, max_nesting), |
      class: "mt-4 d-none replies_form",                             |
      target: "reply.form"                                           |
    }                                                                |
 = tag.div id: "#{dom_id(comment)}_comments" do
- if continue_thread.present? && nesting >= continue_thread && comment.comments.any?
  = link_to "Открыть ветку", url_for(comment: comment.id, anchor: dom_id(comment))
- else
  = render comment.comments, continue_thread: continue_thread, nesting: nesting + 1, max_nesting: local_assigns[:max_nesting]

Мой comments_controller.rb:

class CommentsController < ApplicationController
before_action :authenticate_user!

def create
@comment = @commentable.comments.new(comment_params)
@comment.user = current_user
if @comment.save
  respond_to do |format|
    format.html { redirect_to @commentable }
    format.js
  end
else
  redirect_to @commentable, alert: "Ошибка :("
end
end

def destroy
@comment = @commentable.comments.find(params[:id])
return false unless current_user.id == @comment.user_id

@comment.destroy
redirect_to @commentable
end

private

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

Если я раскомментирую rails-ujs в application.js следующим образом:

require rails-ujs

Тогда, когда я пишукомментарий будет сказано:

ActiveRecord::RecordNotFound in News::CommentsController#create
Couldn't find News with 'id'=artifact-v-spiske-liderov-prodazh-steam-po-itogam-2018-goda

Extracted source (around line #7):

6  def set_commentable
7    @commentable = News.find(params[:news_id])
8  end
9 end

Как я могу это исправить?Спасибо!

1 Ответ

0 голосов
/ 29 декабря 2018

Первое предложение - комментируйте require rails-ujs, пока не решите проблему.Отладка будет проще.

Тогда проблема в том, что как params[:news_id] вы передаете слаг новостей (artifact-v-spiske-liderov-prodazh-steam-po-itogam-2018-goda) вместо идентификатора новостей.Одним из решений является изменение кода для передачи идентификатора новости как params[:news_id].

Другое, немного более уродливое решение заключается в рефакторинге метода set_commentable в News::CommentsController примерно так:

def set_commentable
  @commentable = News.find_by(slug: params[:news_id])
end

Однако это может нарушить другие места, где set_commentable используется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...