Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Association Collection Create Method Failing

#3428

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?

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

State: invalid
Milestone: none
Assigned to: Ryan Bigg Ryan Bigg
Importance: none

Activity

  1. David Trasbo
    David Trasbo
    • 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.

    April 15th, 2010 @ 12:15 PM

  2. Ryan Bigg
    Ryan Bigg
    • 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.

    April 15th, 2010 @ 12:45 PM