简体   繁体   中英

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

This is the error I'm getting:

ActionView::MissingTemplate in Posts#index

Missing partial text_posts/_text_post with {:locale=>[:en], :formats=>[:html],...

Extracted source (around line #5):

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

Here's the code in the file app/views/posts/index.html.erb

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

I'm following along the 'Rails Crash Course' book and this is one of the steps to create a social network. I don't know the reason for the error.

As you're using <%= render @posts %> , i'm am sure this will call the partial file with leading _ symbol on same directory. Please ensure you have already file with the name _posts.html.erb . IF you want to pass the value into partial, here i give you simple illustration :

Assume you have this in customer_controller :

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

Then it instance will available on show.html.erb :

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

These instance variables are available in layouts and partials as well, instead pass variables to partials as locals like:

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

Above line of code will call the file with name _cust_name.html.erb that contains :

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

Hope this helped.

I am assuming that in your posts_controller.rb file you have specified the following:

def index
  @posts = Post.all
end

The reason why you are getting this error is because Rails is trying to display a partial for the variable @posts . What is implicit here, is that Rails is looking for a file named _post.html.erb in the folder app/views/posts/ and not finding anything. To fix this, you will have to manually create the file in that directory ( Note that all partials begin with an underscore ).

Now, if you are wondering what you should put in this partial, first you should know what <%= render @posts %> is doing. When it goes to the partial, it is iterating over all your posts and for each of them, it is going to do something. So your partial may look something like this:

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

Just know that what is implicit here, is that we already have a @posts.each do |post| given for us, so you only have to define whatever content you wish to display for each individual post.

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM