我有投票类,其中投票方法会创建投票实例
这不起作用
def vote(options)
vote = self.votes.create(options)
return vote if vote.valid?
nil
end
这确实有效
def vote(options)
options[:post] = self
vote = self.votes.create(options)
return vote if vote.valid?
nil
end
.create 调用不应自动添加:post association?
澄清
class Post<的ActiveRecord :: Base的 has_many:投票 端
class Vote<的ActiveRecord :: Base的 belongs_to:user,:counter_cache =>真正 belongs_to:post 端
答案 0 :(得分:0)
你有吗
has_many :votes
在你的Post模型中声明?
你在什么时候在对象的生命周期中调用了vote方法?它是回调方法的一部分吗?
答案 1 :(得分:0)
如果将其编写为self.votes.create!(options)
,则调试会更容易,因为它会抛出一个带有错误消息的异常。解决问题后,您可以解决此问题,但是如果不起作用,您应该考虑应该返回的方法。
Post#vote
返回nil
是否有意义?为什么投票失败?您的代码如何处理Post#vote
返回的nil值?
也许你应该把它重写为:
def vote(options)
self.votes.create!(options)
end