CommentsController#index中的ActionController :: UnknownFormat

时间:2019-04-10 08:25:39

标签: ruby-on-rails

我正在尝试创建一个图书馆管理应用程序,并停留在评论模型中

这是我与评论模型的关系:

    class User < ApplicationRecord
       has_many :comments, dependent: :destroy
    end

    class Book < ApplicationRecord
       has_many :comments, dependent: :destroy
    end

    class Comment < ApplicationRecord
       belongs_to :user
       belongs_to :book
       validates :content, presence: true, allow_blank: false
    end

comments_controller.rb

    class CommentsController < ApplicationController
      before_action :load_book, only: :create

    def index
      @q = Comment.ransack(params[:q]) 
  @comments = @q.result.page(params[:page])
    end

    def new;
    end 

    def create   
     @comment = Comment.new(comment_params)
     @comment.user_id = current_user.id
     @comment.book_id = params[:book_id]

     if @comment.save
     flash[:success] = "create_success"
     redirect_to book_path(@book)

    end

    private
    def comment_params
       params.require(:comment).permit(:user_id, :book_id, :content)
    end

    def load_book
      @book = Book.find_by(params[:id])
      return if @book
      flash[:danger] = "books.load_book.error_message"
      redirect_to root_path
     end
     end

在books_controller.rb

    def show
        @comment = Comment.new
end

app / view / books / show.html.erb

    <% provide :title, @book.name %>
    <h1><%= @book.name %></h1>

    <div class="container">
    <dl>
    <dt>Author:</dt><dd><%= link_to @book.author.name, @book.author 
    %></dd><br>
    <dt>Category:</dt><dd>
    <% @book.categories.each do |c|%>
          <%= link_to c.name, c%> |
    <% end %>
    <dt>Publisher:</dt><dd><%= @book.publisher %></dd><br>
    <dt>Page:</dt><dd><%= @book.page %></dd><br>
    <dt>Quantity:</dt><dd><%= @book.quantity %></dd><br>

    </dl>
    <aside>
      <section>
       <%= render 'comments/form' %>  
      </section>
    </aside>
    </div>

app / view / comments / _form.html.erb

    <h3>post_comment</h3>
    <p>
     <%= form_for(@comment) do |f| %>
      <%= f.text_area :content %>
      <%= f.submit "post", class: "btn btn-primary" %>
     <% end %>
    </p>

浏览器显示此错误:

    Missing template comments/new, application/new with {:locale=> 
    [:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, 
    :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * 
    "/home/default/ProjectRails/app/views"

这是我第一次建立多对多关系,可以吗,或者问题出在另一部分?

1 个答案:

答案 0 :(得分:2)

错误消息中已明确指出

CommentsController#index is missing a template for this request format and variant.

您需要创建包含某些内容的文件app/view/comments/index.html.erb