Файл index.js.erb не работает в rails 5.1

1

Я следую учебнику от devfactor.com. Он называется "Let Build: Instagram with Rails". Автор использует AJAX и js файлы в учебнике. Когда добавлен файл под названием "Index.js.erb", он показал много ошибок на моем сервере. Ошибка:

ActionView::Template::Error (Missing partial posts/_posts, application/_posts wi
th {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:raw, :er
b, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "C:/Users/alouftur0/Rails/Photogram/app/views"
  * "C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/kaminari-core-1.0.1/app/views"
  * "C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/devise-4.3.0/app/views"
):
    1: $('#posts').append("<%= escape_javascript(render 'posts')%>");
    2: $('#paginator').html("<%= escape_javascript(link_to_next_page(@posts, 'LO
AD MORE', remote: true, id: 'load_more'))%>");
    3: if (!$('#load_more').length) { $('#paginator').remove(); }

app/views/posts/index.js.erb:1:in '_app_views_posts_index_js_erb___1182481000_10
4067220'

Вот файлы:

application.html.erb:

<!DOCTYPE html>
<html>
  <head>
    <title>Photogram</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
  <%= render 'posts/navbar' %>
  <% flash.each do |key, value| %>
    <div class="alert alert-<%= key %>"><%= value %></div>
  <% end %>
  <%= yield %>
  </body>
</html>

index.html.erb:

<% @posts.each do |post| %>
  <%= render 'post', post: post %>
<% end %>
<div class="text-center" id="paginator">
  <%= link_to_next_page @posts, 'LOAD MORE', remote: true, id: 'load_more' %>
</div>

index.js.erb:

$('#posts').append("<%= escape_javascript(render 'posts')%>");
$('#paginator').html("<%= escape_javascript(link_to_next_page(@posts, 'LOAD MORE', remote: true, id: 'load_more'))%>");
if (!$('#load_more').length) { $('#paginator').remove(); }

application.scss:

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 @import "bootstrap-sprockets";
 @import "bootstrap";

application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require_tree 

Это. Сообщение об ошибке выше. если у вас есть вопросы, просто прокомментируйте это. Спасибо! Вот мой контроллер сообщений:

class PostsController < ApplicationController
    before_action :set_post, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!
    before_action :owned_post, only: [:edit, :update, :destroy]
    def index
      @posts = Post.all.order('created_at DESC').page params[:page]
      respond_to do |format|
        format.js
        format.html
      end
    end

    def show
    end

    def new
      @post = current_user.posts.build
    end

    def create
      @post = current_user.posts.build(post_params)
      if @post.save
        redirect_to posts_path
        flash[:success] = "Post Created!"
      else
        flash.now[:success] = "Your new post couldn't be created!  Please check the form."
        render :new
      end
    end

    def edit
    end

    def update
      if @post.update(post_params)
        redirect_to posts_path
      else
        flash.now[:alert] = "Update failed.  Please check the form."
        render :edit
      end
    end

    def destroy
      @post.destroy
      redirect_to root_path
      flash[:success] = "Destroyed ;)"
    end

    private

    def owned_post
      unless current_user == @post.user
        flash[:success]= "That post doesn't belong to you :("
        redirect_to root_path
      end
    end

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

    def set_post
      @post = Post.find(params[:id])
    end
  end
  • 0
    Добавьте свой контроллер к вопросу.
  • 1
    вот, я добавил это!
Показать ещё 2 комментария
Теги:
ruby-on-rails-5
rubygems

2 ответа

0
Лучший ответ

Вы должны сделать частичным, таким как

$('#posts').append('<%= escape_javascript(render @posts) %>');
  • 0
    Я сделал это, но действие, которое я хотел сделать, не сработало?
  • 0
    но я перестал получать ошибки
Показать ещё 9 комментариев
0

В файле index.html.erb отсутствует элемент #posts для $('#posts').append('<%= escape_javascript(render @posts) %>') в index.js.erb для добавления.

<div id="posts">
  <%= render 'posts' %>
</div>
<div class="text-center" id="paginator">
  <%= link_to_next_page @posts, 'LOAD MORE', remote: true, id: 'load_more' %>
</div> 

Как показывает ошибка, вам также нужны частичные posts/_post.html.erb, которые пытается posts/_post.html.erb частичное JS.

  • 0
    Можете ли вы написать, что мне нужно написать в моих файлах, пожалуйста
  • 0
    У меня уже есть посты / _post.html.erb
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню