【问题标题】:NoMethodError on section 5.7 of Rails GuideRails 指南第 5.7 节的 NoMethodError
【发布时间】:2013-07-04 07:34:55
【问题描述】:

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

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

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 的新手,并尝试完全按照说明进行操作。

我运行的是 Windows 7 x64,带有 Ruby 1.9.3 和 Rails 4.0.0。

这里有一些相关文件;如有其他需要,请告诉我。

posts_controller.rb:

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    只需在create 方法之后写下show 方法,因为您的 show 方法在关键字 private 下方,它被视为 Access Modifier 私有,因此无法通过浏览器直接访问

    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
    

    【讨论】:

    • 非常感谢。我已经坚持了一段时间了。
    • 专业提示不会在类中放散受保护/私有关键字,但对于相关方法添加(下方)private :post_params
    【解决方案2】:

    我在教程中遇到了同样的问题(在这个日期(11/18/14)使用“文章”而不是“帖子”),并发现解决方案是放置以下“def”块在articles_controller.rb 中:

      def show
        @article = Article.find(params[:id])
        end
    

    这对我来说是这样的:

    class ArticlesController < ApplicationController
    def new
        end
    
    def create
        @article = Article.new(article_params)
    
        @article.save
        redirect_to @article
    end
    
    def show
        @article = Article.find(params[:id])
    end
    
    private
    def article_params
        params.require(:article).permit(:title, :text)
    end 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多