This project is archived and is in readonly mode.

#3428 ✓invalid
Alexandre S

Association Collection Create Method Failing

Reported by Alexandre S | October 26th, 2009 @ 08:45 PM

I have a Post class with a vote method which creates a Vote instance

This doesn't work

def vote(options)
   vote = self.votes.create(options)
   return vote if vote.valid?
   nil
end

This does work

def vote(options)
   options[:post] = self
   vote = self.votes.create(options)
   return vote if vote.valid?
   nil
end

Shouldn't the .create call automatically add the :post association?

Comments and changes to this ticket

  • David Trasbo

    David Trasbo April 15th, 2010 @ 12:15 PM

    • Assigned user set to “Ryan Bigg”

    I was unable to duplicate this issue on edge Rails:

    ➜  rails_bugs  ruby ../rails/bin/rails has_many_create --dev
    ...
    ➜  rails_bugs  cd has_many_create 
    ➜  has_many_create  ruby ../../rails/bin/rails g model post title:string
    ...
    ➜  has_many_create  ruby ../../rails/bin/rails g model vote positive:boolean post_id:integer
    ...
    ➜  has_many_create  rake db:migrate
    (in /Users/dtrasbo/code/rails_bugs/has_many_create)
    ...
    ➜  has_many_create  ruby ../../rails/bin/rails c
    Loading development environment (Rails 3.0.0.beta3)
    ruby-1.8.7-p249 > p = Post.create(:title => 'Foo')
     => #<Post id: 1, title: "Foo", created_at: "2010-04-15 11:08:41", updated_at: "2010-04-15 11:08:41"> 
    ruby-1.8.7-p249 > p.vote(:positive => false)
     => #<Vote id: 1, positive: false, post_id: 1, created_at: "2010-04-15 11:08:48", updated_at: "2010-04-15 11:08:48">
    
    class Post < ActiveRecord::Base
      has_many :votes
    
      def vote(attributes)
        vote = votes.create(attributes)
        vote if vote.valid?
      end
    end
    
    class Vote < ActiveRecord::Base
      belongs_to :post
    end
    

    My guess is that this issue is caused by missing associations or foreign keys, e.g. Though I haven't tested to see if this issue exists in 2.3.5 I think this ticket can be marked as invalid - I've never had issues similar to the one described.

  • Ryan Bigg

    Ryan Bigg April 15th, 2010 @ 12:45 PM

    • State changed from “new” to “invalid”

    Do not have a method for creating this, use the built-in helpers:

    post.votes.create(attrs)
    

    Not a Rails bug.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages