This project is archived and is in readonly mode.
Nested objects return extra nil array
-
Denis Odorcic
Can't reproduce unfortunately, anyone else?
-
Aditya Sanghi
- State changed from new to needs-more-info
- Importance changed from to Low
It looks like you're doing a build on a post by default somewhere (perhaps a before_filter somewhere?). Please post part of your controller/model code and clear steps to reproduce the error.
-
Jeff Kreeftmeijer
Automatic cleanup of spam.
-
brpratt (at gmail)
If it was doing a build by default wouldn't that be reflected in the db? Why would Comment.count show 0 and then my app gets an extra comment?
This app is pretty much word-for-word from the rails guide for the blog app...
http://guides.rubyonrails.org/getting_started.htmlI'll repost critical elements here to make it easier.
comments controller:
comments model:class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment]) redirect_to post_path(@post) end def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy redirect_to post_path(@post) end end
posts model:class Comment < ActiveRecord::Base belongs_to :post end
class Post < ActiveRecord::Base validates :name, :presence => true validates :title, :presence => true, has_many :comments end -
brpratt (at gmail)
Interestingly I found in the form:
<h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> <%= f.error_messages %> <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>If I changed the @post.comments.build object to @post.comments.new, it stopped returning a nil object in the array.
-
brpratt (at gmail)
Interestingly I found in the form:
<h2>Add a comment:</h2> <%= form_for([@post, @post.comments.build]) do |f| %> <%= f.error_messages %> <div class="field"> <%= f.label :commenter %><br /> <%= f.text_field :commenter %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>If I changed the @post.comments.build object to @post.comments.new, it stopped returning a nil object in the array.
-
Aditya Sanghi
- State changed from needs-more-info to invalid
Marking ticket as invalid for now as it's clear where your object is coming from.
Please see documentation related to active record. It is clear that @post.comments.build is the way to build associations (not new).
Doing build will create an object but not save it of course.