Ajax: remote => true не работает

Я получаю синтаксическую ошибку, когда пытаюсь добавить в свои формы ajax. Я пытаюсь сделать так, чтобы каждый раз, когда человек комментирует, он не обновлялся. Я пробовал менять контроллеры и добавил format.js, но все равно получаю сообщение об ошибке.

<%= simple_form_for ([post, post.comments.new], remote: true) do |f| %>

/app/views/posts/_post.html.erb:41: syntax error, unexpected ',', expecting ')' or ([post, post.comments.new], remote: true) do |f| @output_ ^
/app/views/posts/_post.html.erb:51: syntax error, unexpected keyword_ensure, expecting end-of-input ensure ^

Просмотреть файл

<div class = "posts-wrapper">
    <div class = "post">
        <div class = "post-head">
            <div class = "thumb-img"></div>
            <div class = "user-name">
                <%= post.user.user_name %>
            </div>
        </div>
        <div class = "image center-block">
            <%= link_to (image_tag post.image.url(:medium), class:'img-responsive'), post_path(post) %>
        </div>
        <div class = "post-bottom">
            <div class = "user-name-comment">
                <%= post.user.user_name %>
            </div>
            <div class = "caption">
                <%= post.caption %>
            </div>
            <% if post.comments %>
                <% post.comments.each do |comment| %>
                    <div class = "comment">
                        <div class = "user-name">
                            <%= comment.user.user_name %>
                        </div>
                        <div class = "comment-content">
                            <%= comment.content %>
                        </div>
                        <% if comment.user == current_user %>
                            <%= link_to post_comment_path(post, comment), method: :delete, data: { confirm: "Are you sure?" } do %>
                                <i class = "fas fa-trash-alt fa-2x" style = "padding: 5px; float: right; margin-top: -36px;"></i>
                            <% end %>
                        <% end %>
                    </div>
                <% end %>
            <% end %>
        </div>

        <div class = "comment-like-form row">
            <div class = "like-button col-sm-1">
              <i class = "far fa-heart fa-2x"></i>
                <div class = "comment-form col-sm-11">
                    <%= simple_form_for ([post, post.comments.new], remote: true) do |f| %>
                        <%= f.text_field :content, class: 'arthur_form', placeholder: 'Add a comment...' %>
                        <%= f.button :submit, class: "btn btn-primary padding: 50px;" %>
                    <% end %>
                </div>
            </div>
        </div>
    </div>
</div>

Комментарий контроллера

class CommentsController < ApplicationController
    before_action :set_post

    def create
        @comment = @post.comments.new(comment_params)
        @comment.user_id = current_user.id

        if @comment.save
            flash[:success] = "Comment succesfully created."
            respond_to do |format|
                format.html { redirect_to post_index_path }
                format.js
            end
        else
            flash[:alert] = "Check the comment form, something went horribly wrong."
            respond_to do |format|
                format.html { redirect_to post_index_path }
                format.js
            end
        end
    end


    def destroy
        @comment = @post.comments.find(params[:id])
        @comment.destroy
        flash[:alert] = "Comment Deleted."
        redirect_to post_index_path
    end

    private

    def comment_params
      params.require(:comment).permit(:content)
    end

    def set_post
      @post = Post.find(params[:post_id])
    end
end

Пост контролера

class PostsController < ApplicationController
    before_action :authenticate_user!
    before_action :owned_post, only: [:edit, :update, :destroy]

    def index
        @posts = Post.all
    end

    def new
        @post = current_user.posts.new
    end

    def show
        @post = Post.find(params[:id])
    end

    def create
        @post = current_user.posts.build(post_params)

        if @post.save
            flash[:success] = "Your post has been created!"
            respond_to do |format|
                format.html { redirect_to posts_path }
                format.js
            end
        else
            flash[:alert] = "Your new post couldn't be created!  Please check the form."
            render :new
        end
    end

    def edit
        @post = Post.find(params[:id])
    end

    def update
        if @post = Post.find(params[:id])
            flash[:success] = "Post updated."
            @post.update(post_params)
            redirect_to(post_path(@post))
            flash.now[:alert] = "Update failed.  Please check the form."
        else
        end
    end

    def destroy
        @post = Post.find(params[:id])
        @post.destroy
        redirect_to posts_path
    end

    private

    def post_params
        params.require(:post).permit(:image, :caption)
    end

    def owned_post
        @post = Post.find(params[:id])
        unless current_user == @post.user
            flash[:alert] = "That post doesn't belong to you!"
            redirect_to post_index_path
        end
    end
end

Какой у Вас вопрос?

sawa 11.06.2018 10:17

Проверьте синтаксическую ошибку в /app/views/posts/_post.html.erb в строках 41 и 51.

Akash Pinnaka 11.06.2018 10:31

Я пытаюсь добавить remote: true в simple_form, но получаю синтаксическую ошибку. Я пытаюсь добавить ajax в свои формы, чтобы, когда пользователь комментирует, не обновляется вся страница. github.com/ArthurTruong5/ArthurGram

Arthur Truong 11.06.2018 10:33
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
3
3
72
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Измените инициализацию формы с помощью:

<%= simple_form_for [post, post.comments.new], remote: true do |f| %>

Кронштейн не нужен.

Другие вопросы по теме