R – Treacherous ActiveRecord behavior

rails-activerecordruby-on-rails

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?

CLARIFICATION

class Post < ActiveRecord::Base
has_many :votes
end

class Vote < ActiveRecord::Base
belongs_to :user, :counter_cache => true
belongs_to :post
end

Best Solution

Do you have

has_many :votes

declared in your Post model?

At what point are you calling the vote method in the object's lifecycle? It it part of a callback method?

Related Question