Alex Panait
Alex Panait

Reputation: 33

Rails 3 Render / Partial

I'm very new to Rails 3 and I've followed some tutorials and now I'm trying to "play" with the code created. I have followed the tutorial from http://guides.rubyonrails.org/getting_started.html

I'm am trying to render the form for new posts on the homepage with this code:

<%= render :partial => "posts/form" %>

The posts/_form.html.erb looks like this:

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

and this is the error I get:

 undefined method `model_name' for NilClass:Class
Extracted source (around line #1):

1: <%= form_for(@post) do |f| %>
2:   <% if @post.errors.any? %>
3:     <div id="error_explanation">
4:       <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb

Rails.root: d:/server/cazare

Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'

I understand that this may seem a piece of cake for some of you but I'm trying to understand how everything works on Rails so I hope you can understand me.

Thanks in advance !

Upvotes: 3

Views: 4266

Answers (3)

Thaha kp
Thaha kp

Reputation: 3709

In the posts/_form.html.erb,

change

 <%= form_for(@post) do |f| %>

to

<%= form_for(Post.new) do |f| %>

Upvotes: 0

Chowlett
Chowlett

Reputation: 46675

Rails is attempting to build a form for the object @post. In order to do that, it needs to know what sort of object @post is; that way, it can find any existing data in the object and fill it into the form for you. Rails has a method grafted on to objects called model_name to do the lookup, but it won't be grafted onto NilClass (the class of the nil object).

I suspect that you haven't defined @post anywhere - it's an instance variable of the Controller, so you'd expect the controller to either find @post from the database, or to call @post = Post.new - so it's nil.

Upvotes: 1

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

@post variable is not instantiated in the Controller :)

so "@post = Post.new" inside the controller action should do the trick

Upvotes: 5

Related Questions