首页 > 解决方案 > 模板丢失错误 - Ruby on Rails

问题描述

我的项目有一个用户添加的书籍列表。用户可以评论添加的书籍。同时要求评论“标题”和“内容”。

但是,对于comment.rb模型中的这两个属性

    validates :title, presence: true
    validates :content, presence: true

添加时出现此错误。删除这些功能时,我没有收到任何错误。

Missing template comments/new, application/new with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}.

评论控制器.rb

def create
  @book = Book.find(params[:book_id])
  @comment = @book.comments.new(comment_params)
  @comment.user_id = current_user.id
  @comment.status = "unapproved"
  if @comment.save
    redirect_to book_path(@book), notice: "Comment was successfully created."
  else
    render :new #It gives an error here
  end
end

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

comments.rb 模型

class Comment < ApplicationRecord
  belongs_to :book
  belongs_to :user
  scope :approved, -> { where status: 'approved'}
  scope :unapproved, -> { where status: 'unapproved'}
  validates :title, presence: true
  validates :content, presence: true
end

标签: ruby-on-railsruby

解决方案


Rails 在尝试从操作中渲染文件时抛出一个Exception错误,并且没有在它检查的默认路径中找到它。

根据您在控制器中的代码,该文件app/views/comments/new.html.erb必须存在,以便控制器操作可以在创建comment记录时验证失败时呈现它。


推荐阅读