首页 文章

奸诈的ActiveRecord行为?

提问于
浏览
0

我有一个带有 vote 方法的 Post 类,它创建了一个 Vote 实例

这不起作用

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关联?

澄清

class Post <ActiveRecord :: Base has_many:投票结束

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

2 回答

  • 0

    你有没有

    has_many :votes
    

    在你的Post模型中声明?

    你在什么时候在对象的生命周期中调用了vote方法?它是回调方法的一部分?

  • 0

    如果你把它写成 self.votes.create!(options) 会更容易调试,因为它会抛出一个带有错误信息的异常 . 解决问题后,您可以解决此问题,但是如果不起作用,您应该考虑应该返回的方法 .

    Post#vote 返回 nil 是否有意义?为什么投票失败?你的代码如何处理 Post#vote 返回的nil值?

    也许你应该重写它:

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

相关问题