危险的 ActiveRecord 行为?
我有一个带有 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 关联?
CLARIFICATION
类帖子 < ActiveRecord::基础 has_many : 投票 末班
投票< ActiveRecord::基础 属于:用户,:counter_cache =>真的 属于:帖子 结尾
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你已经
在你的Post模型中声明了吗?
您在对象生命周期的什么时候调用 vote 方法?它是回调方法的一部分吗?
Do you have
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?
如果将其编写为
self.votes.create!(options)
,调试起来会更容易,因为这样它会抛出带有错误消息的异常。一旦解决了问题,您就可以将其删除,但是您应该考虑如果它不起作用,您的方法应该返回什么。Post#vote
返回nil
有意义吗?为什么投票会失败?您的代码如何处理Post#vote
返回的 nil 值?也许你应该将其重写为:
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 returnnil
? Why should casting a vote fail? How does your code handle the nil value returned byPost#vote
?Maybe you should just re-write it as: