1

我正在关注位于此处的 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。

以下是一些相关文件;请让我知道是否需要其他任何内容。

post_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

显示.html.erb:

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

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

新的.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 %>
4

2 回答 2

2

show只需在方法之后写下create方法,因为您的 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
于 2013-07-04T07:36:59.663 回答
1

我在教程中遇到了同样的问题(在这个日期(11/18/14)使用'articles'而不是'posts'),并发现解决方案是在articles_controller中放置以下“def”块。 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
于 2014-11-18T20:53:27.177 回答