Rails 3 - Controller 'new' action with nested resource returning 'NoMethodError' -


i created message board application , uses following 3 models work whole thing: forums have many topics, , topics have many posts. posts nested resource of topic, , whenever user chooses "create new topic," 'new' action has nested post start thread. here relative code of that...

topics_controller.rb

class topicscontroller < applicationcontroller   load_and_authorize_resource   def new     @topic = topic.new     @post = @topic.posts.build      respond_to |format|       format.html # new.html.erb       format.xml  { render :xml => @topic }     end    end     [...] 

topic.rb

class topic < activerecord::base   has_many :posts   belongs_to :user, :counter_cache => true   belongs_to :forum, :counter_cache => true   validates :title, :length => { :maximum => 95 }, :presence => { :message => "you need title topic." }    accepts_nested_attributes_for :posts end 

post.rb

class post < activerecord::base   belongs_to :user, :counter_cache => true   belongs_to :forum, :touch => true, :counter_cache => true    belongs_to :topic, :touch => true, :counter_cache => true     validates :body, :presence => { :message => "you have not written text in body." } end 

new.html.erb

<%= form_for(@topic, :url => forum_topics_path) |f| %>    <%= f.label :title %><%= f.text_field :title %>     <%= fields_for(@post) |cf|%>       <%= cf.label :body %><%= cf.text_area :body, :cols=> 108, :rows => 10 %>    <% end %>     <%= f.submit  %> <% end %> 

anyway, completed , worked fine.

up until now. out of blue no reason can spot whatsoever, whenever select "create new topic" , directed 'new' action on topics, error of "nomethoderror in topics#new: have nil object when didn't expect it! might have expected instance of array. error occurred while evaluating nil.[]"

this makes absolutely no sense looked @ previous versions in git, , there have been no earth shattering changes made code. perhaps updated rails version (3.0.7) or gem responsible, dunno that.

anyway, line it's throwing fit on in html.erb file, <%= fields_for(@post) |cf|%>. uh...it's new it's supposed nil, right? take out, , works. i've tried redefining @post in topic controller post.new, returns same error. in addition, i've googled on subject says @post = @topic.posts.build way go.

so doing wrong in code above? , idea why work previously, not now?

try this, make sure it's f.fields_for , not fields_for.

<%= form_for(@topic, :url => forum_topics_path) |f| %>    <%= f.label :title %><%= f.text_field :title %>     <%= f.fields_for(@post) |cf|%>       <%= cf.label :body %><%= cf.text_area :body, :cols=> 108, :rows => 10 %>    <% end %>     <%= f.submit  %> <% end %> 

Comments