简体   繁体   中英

Nomethod error in the show template

show.html.erb

<% @posts.each do |post|%>
  <h1><strong>Title</strong></h1> 
  <%= post.Title.upcase %>
  <h2><i>name</i></h2>
  <%= post.Name.capitalize %>
  <p>
  <b>Message</b>
  <%=post.Message %>
  </p>
<% end -%>

post controller

class PostsController < ApplicationController
  def index
    @posts =Post.all
  end

  def new
    @posts =Post.new  
  end

  def create#no view just for the saving process
    @posts = Post.new(ok_params)
    if @posts.save
      redirect_to posts_path
    else
      render 'new'
    end
  end

  def show#we will use it to view the whole mesage
    @posts=Post.find(params[:id])
  end

  def edit
    @posts=Post.find(params[:id])
  end

  def update
    @posts=Post.find(params[:id])
    if @posts.update_attributes(ok_params)
      redirect_to posts_path
    else
      render 'new'
    end
  end

  def destroy
    @posts=Post.find(params[:id])
    @posts.destroy

    redirect_to posts_path
  end

  private

  def ok_params
    params.require(:post).permit(:Title, :Name, :Message, :Comments)
  end
end

But when the app run in the server(which i use thin instead of puma) it indicates a NoMethod error of "unidentified method ##each" the NoMethod error in the show template

This is happening because in your show action you are setting your @posts variable to a single Post instance, not an Enumerable collection. So it cannot be iterated over with a #each .

in your show you are only wanting to display a single Post, yes? if so, you do not need to use .each, just change your show to:

<h1><strong>Title</strong></h1> 
<%= @post.Title.upcase %>
<h2><i>name</i></h2>
<%= @post.Name.capitalize %>
<p>
  <b>Message</b>
  <%= @post.Message %>
</p>

and change your controllers show action to:

def show # we will use it to view the whole mesage
  @post = Post.find(params[:id])
end

use the singular instead of the plural, as you are assigning just a single instance.

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