Note that there are some explanatory texts on larger screens.

plurals
  1. PORails : Why nil object in my view
    primarykey
    data
    text
    <p>I have created a very simple Rails 3.1 app with basic stuffs like following:</p> <p>My <strong>PostsController.rb</strong> has <code>new</code>, <code>index</code>, <code>create</code> methods:</p> <pre><code>def index @posts = Post.all render :index end def new @post = Post.new render :new end def create @post = Post.new(params[:post]) if @post.save render :index else render :new end end </code></pre> <p>The <strong>new.html.erb</strong> form:</p> <pre><code>&lt;%= form_for @post do |f| %&gt; &lt;%= f.error_messages%&gt; &lt;p&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.label :address %&gt;&lt;br /&gt; &lt;%= f.text_field :address, :size=&gt;60 %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.submit 'Create' %&gt; &lt;/p&gt; &lt;% end %&gt; </code></pre> <p>the index view (<strong>index.html.erb</strong>):</p> <pre><code>&lt;table&gt; &lt;% @posts.each do |post| %&gt; &lt;tr&gt; ... &lt;/tr&gt; &lt;% end %&gt; &lt;/table&gt; </code></pre> <p>my <strong>routes.rb</strong> has defined:</p> <pre><code>resources :posts root :to =&gt; 'post#new' </code></pre> <p>With all above, when the new form is submited, the <code>create</code> method in <strong>PostController</strong> will be invoked, then inside the <code>create</code> method, if the new post is saved successfully, it will <code>render :index</code>,that's to render the <strong>index.html.erb</strong> view, things are fine at this point. but I got a error now in <strong>index.html.erb</strong> view:</p> <p>It complains that the <strong>@posts</strong> in <code>&lt;% @posts.each do |post| %&gt;</code> is <strong>nil</strong>, why???</p> <p><strong>-------------I also tried-------------------------</strong></p> <p>I tried to use <code>redirect_to posts_path</code> in <code>create</code> method, then I got <strong>undefined method `posts_path_url'</strong> error</p> <p>I also tried to use <code>redirect_to :index</code> in <code>create</code> method, then I got <strong>undefined method `index_url'</strong> error</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload