显示模板中的Nomethod错误

时间:2017-02-08 08:08:37

标签: ruby-on-rails

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

帖子控制器

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

但是,当应用程序在服务器中运行时(我使用的是瘦而不是美洲豹),它表示NoMethod错误&#34;未识别的方法##每个&#34;   the NoMethod error in the show template

1 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为在您的show动作中,您将@posts变量设置为单个Post实例,而不是Enumerable集合。所以它不能用<h1><strong>Title</strong></h1> <%= @post.Title.upcase %> <h2><i>name</i></h2> <%= @post.Name.capitalize %> <p> <b>Message</b> <%= @post.Message %> </p> 迭代。

在你的节目中你只想展示一个帖子,是吗?如果是这样,你不需要使用.each,只需将你的节目改为:

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

并将您的控制器显示操作更改为:

{{1}}

使用单数而不是复数,因为您只分配一个实例。