Rails入门教程部分不适用于新的博客帖子

时间:2014-05-08 14:32:24

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 renderpartial

我正在通过轨道工作"入门"教程,我在他们引入部分内容时陷入了困境。由于某些原因,当从new.html.erb渲染时,部分不起作用,尽管从edit.html.erb渲染时它确实有效。点击"新"要访问new.html.erb,我收到以下错误:

错误:

"表格中的第一个参数不能包含nil或为空" 对于以下部分中的第一行:

_form.html.erb:

<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
    <h2><%= pluralize(@post.errors.count, "error") %> prohibited
        this article from being saved:</h2>
    <ul>
        <% @post.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
        <% end %>
    </ul>
</div>
<% end %>
<p>
    <%= f.label :title %><br/>
    <%= f.text_field :title %>
</p>

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

</p>

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

new.html.erb:

<h1>New Post</h1>

<%= render 'form' %>

<%= link_to 'Back', posts_path %>

edit.html.erb:

<h1>Edit post</h1>

<%= render 'form' %>

<%= link_to 'Back', posts_path %>

posts_controller.rb:

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

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

    if @post.update(post_params)
      redirect_to @post
    else
      render 'edit'
    end
  end
  ...

看起来new.html.erb不知道@post变量是否属于新帖子。最初的new.html.erb看起来像这样:

<h1>New Post</h1>

   <%= form_for :post, url: posts_path do |f| %>        
     ...

...除了使用符号而不是@post之外,它与部分表格相同。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您未在@post操作中设置Posts#new实例变量(这就是nil的原因)。你应该:

def new
  @post = Post.new
end

PostsController中。

相关问题