Вопрос

I'm working my way through the rails "Getting Started" tutorial, and I'm stuck at the point where they introduce partials. For some reason the partial doesn't work as described when rendered from new.html.erb, although it does work when rendered from edit.html.erb. When clicking "New" to get to the new.html.erb, I'm getting the following error:

Error:

"First argument in form cannot contain nil or be empty" for the first line in the following partial:

_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
  ...

It looks as though the new.html.erb doesn't know about the @post variable if it's a new post. The original new.html.erb looked like this:

<h1>New Post</h1>

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

... other than the use of symbols instead of @post, it's identical to the partial form.

Any ideas?

Это было полезно?

Решение

You don't set @post instance variable in your Posts#new action (and that's why it's nil). You should have:

def new
  @post = Post.new
end

in your PostsController.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top