У меня проблемы со следующим кофейнистом:
jQuery ->
# Create a comment
$(".comment-form")
.on "ajax:beforeSend", (evt, xhr, settings) ->
$(this).find('textarea')
.addClass('uneditable-input')
.attr('disabled', 'disabled');
.on "ajax:success", (evt, data, status, xhr) ->
$(this).find('textarea')
.removeClass('uneditable-input')
.removeAttr('disabled', 'disabled')
.val('');
$(xhr.responseText).hide().insertAfter($(this)).show('slow')
# Delete a comment
$(document)
.on "ajax:beforeSend", ".comment", ->
$(this).fadeTo('fast', 0.5)
.on "ajax:success", ".comment", ->
$(this).hide('fast')
.on "ajax:error", ".comment", ->
$(this).fadeTo('fast', 1)
В принципе, у меня есть пользовательская форма, в которую я добавляю комментарии. Когда добавляется новый комментарий, он должен изменить класс и отключить текстовое поле перед отправкой данных в базу данных. Затем он должен сбросить класс, очистить текстовое поле и снова включить текстовое поле. Затем, наконец, он должен добавить новый комментарий после текстового поля.
Первая часть кода работает, и класс добавляется в текстовое поле, и он отключен, но остальная часть скрипта никогда не происходит. Конечно, комментарий фактически сохраняется в базе данных, и обновление страницы покажет комментарий.
Я пережил это много раз и не могу понять, что происходит не так. У меня была более ранняя проблема с неправильным вложением текста в сценарий, но это было исправлено.
Мой код CommentController выглядит следующим образом:
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :destroy]
def create
@comment_hash = comment_params
@obj = @comment_hash[:commentable_type].constantize.find(@comment_hash[:commentable_id])
# Not implemented: check to see whether the user has permission to create a comment on this object
@comment = Comment.build_from(@obj, current_user, @comment_hash[:body])
@comment.user = current_user
if @comment.save
render partial: "comments/comment", locals: { comment: @comment }, layout: false, status: :created
else
p @comment.errors
render js: "alert('error saving comment');"
end
end
def destroy
if @comment.destroy
render json: @comment, status: :ok
else
render js: "alert('error deleting comment');"
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit( :commentable_id, :commentable_type, :body, :user_id)
end
end
Здесь моя форма для создания комментариев:
<div class='comment-form'>
<%= simple_form_for comment, remote: true do |f| %>
<%= f.input :body, input_html: { rows: "2" }, label: false %>
<%= f.input :commentable_id, as: :hidden, value: comment.commentable_id %>
<%= f.input :commentable_type, as: :hidden, value: comment.commentable_type %>
<%= f.button :submit, 'Save Note', class: "button tiny radius", disable_with: "Submitting…" %>
<% end %>
</div>
И вот мой код для показа комментариев:
<div class='comment'>
<hr>
<%=link_to "×", comment_path(comment), method: :delete, remote: true, data: { confirm: 'Are you sure you want to remove this comment?',disable_with: 'x' }, class: 'close' %>
<small><%=comment.updated_at.to_s(:short) %></small>
<p><%= comment.body %></p>
Кстати, действие удаления частично работает. Он удаляет комментарий из базы данных и скрывает все комментарии. Обновление страницы показывает комментарии, которые не были удалены.
Любая помощь будет принята с благодарностью, так как я не знаю, с чем это связано. На мой взгляд, он должен работать, поэтому я должен пропустить что-то простое.
Это проблема с вашим отступом. Строка .on "ajax:success"
должна быть отступом на том же уровне, что и другой .on
. И следующий код должен также иметь отступ:
jQuery ->
# Create a comment
$(".comment-form")
.on "ajax:beforeSend", (evt, xhr, settings) ->
$(this).find('textarea')
.addClass('uneditable-input')
.attr('disabled', 'disabled');
.on "ajax:success", (evt, data, status, xhr) -> #<-- this line!
$(this).find('textarea')
.removeClass('uneditable-input')
.removeAttr('disabled', 'disabled')
.val('');
$(xhr.responseText).hide().insertAfter($(this)).show('slow')
.on "ajax:success"
этот.on "ajax:success"
? Смотрите мое редактирование в суть ...