1
votes

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

2
How does it not work? Further explanation is required.Ryan Bigg

2 Answers

1
votes

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?

0
votes

It would be easier to debug if you wrote it as self.votes.create!(options) because then it will throw an exception with an error message. You can take this out once you fix the problem, but you should think about what your method should return if it doesn't work.

Does it make sense for Post#vote to return nil? Why should casting a vote fail? How does your code handle the nil value returned by Post#vote?

Maybe you should just re-write it as:

def vote(options)
  self.votes.create!(options)
end