簡體   English   中英

我在新的Rails應用程序中創建了一個文件,當我運行http:// localhost頁面時,我收到一條Missing Template錯誤消息

[英]I created a file in my new rails app and when I run the http://localhost page I get a Missing Template error message

這是我得到的錯誤:

Posts#index中的ActionView :: MissingTemplate

缺少帶有{:locale => [:en] 、: formats => [:html],...的部分text_posts / _text_post ...

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

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

這是文件app / views / posts / index.html.erb中的代碼

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

我遵循的是“ Rails Crash Course”這本書,這是創建社交網絡的步驟之一。 我不知道錯誤的原因。

當您使用<%= render @posts %> ,我確定這將在同一目錄中調用帶有前導_符號的部分文件。 請確保您已經使用_posts.html.erb 如果您要將值傳遞給partial,在這里我給您簡單的說明:

假設您在customer_controller具有以下內容:

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

然后它的實例將在show.html.erbshow.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>

希望這會有所幫助。

我假設在您的posts_controller.rb文件中指定了以下內容:

def index
  @posts = Post.all
end

之所以出現此錯誤,是因為Rails試圖顯示變量@posts部分內容 這里隱含的是,Rails在文件夾app/views/posts/尋找名為_post.html.erb的文件,但未找到任何內容。 要解決此問題,您將必須在該目錄中手動創建文件( 請注意,所有部分均以下划線開頭 )。

現在,如果您想知道應該在此部分中放入什么,首先應該知道<%= render @posts %>在做什么。 當涉及局部時,它將遍歷您的所有帖子,對於每個帖子,它都會做某事。 所以您的部分可能看起來像這樣:

<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| 為我們提供的信息,因此您只需定義希望為每個帖子顯示的內容即可。

希望這可以幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM