11

我正在制作一个网站,该网站有一个用户页面,应该允许用户创建公告帖子。

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

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 %>

用户控制器:

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

公告控制器:

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

我已检查是否可以在控制台中手动创建公告。我究竟做错了什么?

4

3 回答 3

11

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

通常,创建操作会使用表单重新呈现模板。通常这就是new行动,这意味着增加行动render "new"else一部分create

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

render "shared/announcements_form"

到你的create行动。

于 2013-09-01T11:38:06.593 回答
1

像您在成功保存公告时所做的那样在该块中放置一个redirect_to或将解决问题。render "shared/announcements_form"else

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

于 2013-09-01T11:37:10.630 回答
0

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

于 2014-05-25T02:26:54.533 回答