本文介绍了Rails 指南第 5.7 节中的 NoMethodError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注位于此处的 Rails 4.0.0 入门教程:http://guides.rubyonrails.org/getting_started.html

I'm following the Getting Started tutorial for Rails 4.0.0 located here:http://guides.rubyonrails.org/getting_started.html

我在第 5.7 节中应该得到 ActiveModel::ForbiddenAttributes 错误.相反,我收到此错误:

I'm at the point in section 5.7 where I'm supposed to be getting the ActiveModel::ForbiddenAttributes error. Instead, I get this error:

NoMethodError in Posts#show

Showing C:/Rails/blog/app/views/posts/show.html.erb where line #8 raised:

undefined method `text' for nil:NilClass
Extracted source (around line #8):
5
6  <p>
7    <strong>Text:</strong>
8    <%= @post.text %>
9 </p>

尽管如此,我相信帖子正在被创建,因为每次我提交表单时 ID 都会增加.我是 Rails 的新手,并试图完全按照说明进行操作.

Despite this, I believe the posts are being created, since the ids are being incremented each time I submit the form. I am brand new to Rails, and have attempted to exactly follow the instructions.

我运行的是 Windows 7 x64,使用 Ruby 1.9.3 和 Rails 4.0.0.

I'm running Windows 7 x64, with Ruby 1.9.3 and Rails 4.0.0.

这里有一些相关的文件;如果需要其他任何内容,请告诉我.

Here are some relevant files; please let me know if any other are required.

class PostsController < ApplicationController
def new
end

def create
   @post = Post.new(post_params)

  @post.save
  redirect_to @post
end

private
  def post_params
    params.require(:post).permit(:title, :text)
  end

def show
  @post = Post.find(params[:id])
end

end

show.html.erb:

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>

new.html.erb

<h1>New Post</h1>

<%= form_for :post, url: posts_path do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

推荐答案

只需在 create 方法之后写下 show 方法,因为你的 show 方法在关键字 private 将私有作为 Access Modifier,因此不能直接通过浏览器访问

Just write down show method after create method, as your show method is below the keyword private it is taking private as a Access Modifier and hence can't access directly through browser

class PostsController < ApplicationController
  def new
  end

  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to @post
  end

  def show
    @post = Post.find(params[:id])
  end

  private
    def post_params
      params.require(:post).permit(:title, :text)
    end
end

这篇关于Rails 指南第 5.7 节中的 NoMethodError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:40