【问题标题】:I created a file in my new rails app and when I run the http://localhost page I get a Missing Template error message我在我的新 Rails 应用程序中创建了一个文件,当我运行 http://localhost 页面时,我收到一条 Missing Template 错误消息
【发布时间】:2015-10-27 14:50:24
【问题描述】:

这是我得到的错误:

ActionView::MissingTemplate in Posts#index

缺少部分 text_posts/_text_post 和 {:locale=>[:en], :formats=>[:html],...

提取的源代码(第 5 行附近):

    3 </div>
    4
    5 <%= render @posts %>

这是文件 app/views/posts/index.html.erb 中的代码

    <div class="page-header">
    <h1>Home</h1>
    </div>
    <%= render @posts %>

我正在遵循“Rails 速成课程”一书,这是创建社交网络的步骤之一。我不知道错误的原因。

【问题讨论】:

  • 您是否已经创建了文件_posts.html.erb
  • 我不明白“text_posts”是从哪里来的?

标签: ruby-on-rails localhost


【解决方案1】:

我假设您在posts_controller.rb 文件中指定了以下内容:

def index
  @posts = Post.all
end

您收到此错误的原因是 Rails 试图为变量 @posts 显示 部分。这里隐含的是,Rails 正在文件夹 app/views/posts/ 中寻找一个名为 _post.html.erb 的文件,但没有找到任何东西。要解决此问题,您必须手动创建该目录中的文件(请注意,所有部分都以下划线开头)。

现在,如果您想知道应该在这个部分中添加什么,首先您应该知道&lt;%= render @posts %&gt; 在做什么。当它进入部分时,它会遍历您的所有帖子,并且对于每个帖子,它都会做一些事情。所以你的部分可能看起来像这样:

<p>
  <%= link_to post.title, post_path(post.id) %>
</p>
<p>
  <%= link_to "Edit", edit_post_path %>
</p>
<p>
  <%= link_to "Delete", post_path(post.id), method: :delete %>
</p>

只要知道这里隐含的是我们已经为我们提供了@posts.each do |post|,因此您只需定义您希望为每个帖子显示的任何内容。

希望这会有所帮助!

【讨论】:

  • 我创建了该文件,但仍然收到相同的缺少模板错误消息。在创建文件(例如生成某些内容或迁移)后,我是否必须做其他事情?你还提到了@posts.each 做 |post|该文件将位于哪个文件中?
  • 没关系,我得工作了。非常感谢你很有帮助
【解决方案2】:

当您使用&lt;%= render @posts %&gt; 时,我确信这将调用同一目录中带有前导_ 符号的部分文件。请确保您已经提交了名称为_posts.html.erb 的文件。如果您想将值传递给部分,这里我给您简单的说明:

假设您在customer_controller 中有这个:

def show
 @customer= Customer.find(params[:id])
end

然后它的实例将在show.html.erb 上可用:

<p>Item: <%= @customer.name%></p>

这些实例变量在布局和局部变量中也可用,而是将变量作为局部变量传递给局部变量,例如:

// here is the same concept with your problem
// render "cust_name" find the filename leading with underscore
<%= render "cust_name", name: @customer.name%>

以上代码行将调用名称为_cust_name.html.erb 的文件,其中包含:

<h1><%= name %></h1>

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2014-10-25
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多