开发者

Treacherous ActiveRecord behavior?

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)
   开发者_如何学Creturn 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


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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜