如何修复丢失的模板错误?

时间:2013-09-01 11:28:14

标签: ruby-on-rails ruby forms validation

我正在创建一个网站,其中包含一个允许用户创建公告帖子的用户页面。

当我尝试通过网站创建新的公告帖时,会弹出如下错误:

Template is missing
Missing template announcements/create, application/create with {:locale=>[:en],     :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: * ".../app/views"

如果我在该位置创建create.html.erb,表单将一如既往地返回false。

用户页面(/app/view/users/show.html.erb):

<% provide(:title, 'Admin Page') %>

<% if signed_in? %>
  <div class="container">
    <%= link_to "Sign out", signout_path, method: "delete" %>
    <br />

     <% if @announcements.any? %>
      <h3>Announcements (<%= @announcements.count %>)</h3>
      <ol>
        <%= render @announcements %>
      </ol>
      <%= will_paginate @announcements %>
    <% end %>

      <%= render 'shared/announcement_form' %>
  </div>

<% else %>
<script type="text/javascript"> window.location.href= '<%= signin_path %>' </script>
<% end %>

共享/ _announcement_form.html.erb:

<%= form_for(@announcement) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

   <div class="field">
    <%= f.text_area :title, placeholder: "Compose new title..." %>
  </div>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new announcement..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

UsersController:

class UsersController < ApplicationController
  def new
  end

  def show
    @user = User.find(params[:id])
    @announcement = current_user.announcements.build if signed_in?
    @announcements = @user.announcements.paginate(:page => params[:a_page], :per_page  => 10)
  end
end

AnnouncementsController:

class AnnouncementsController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy]

  def create
    @announcement = current_user.announcements.build(announcement_params)

    if @announcement.save
      flash[:success] = "Announcement created!"
      redirect_to root_url
    else
      flash[:error] = "Failed to create announcement!"
    end
  end

  def destroy
  end

  private

  def announcement_params
    params.require(:announcement).permit(:content)
    params.require(:announcement).permit(:title)
  end
end

我已经检查过我可以在控制台中手动创建通知。我做错了什么?

3 个答案:

答案 0 :(得分:9)

如果@announcement无法保存AnnouncementsController#create,则会呈现操作的默认视图 - 在这种情况下create.html.erb不存在。因此,您会收到您所看到的错误。

通常,create动作会使用表单重新呈现模板。通常这是new操作,这意味着将render "new"添加到else操作的create部分。

但是,在你的情况下,似乎它在"shared/announcements_form"部分,这意味着要添加

render "shared/announcements_form"

create行动。

答案 1 :(得分:1)

在成功保存通知时,在redirect_to块中放置render "shared/announcements_form"else就可以解决问题。

您尝试创建的通知无法保存,因此会执行else块,这就是尝试呈现announcements/create.html.erb的内容。按照惯例,如果操作中没有任何显式render,Rails会尝试呈现与该操作对应的任何视图。

答案 2 :(得分:0)

检查您的路径,确保您的完整路径拼写正确(即文件夹),而不仅仅是文件名。在我的拼写错误修复文件夹名称后,它工作。