危险的 ActiveRecord 行为?

发布于 2024-08-08 22:19:40 字数 598 浏览 3 评论 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 关联?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

舞袖。长 2024-08-15 22:19:40

你已经

has_many :votes

在你的Post模型中声明了吗?

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

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?

无人问我粥可暖 2024-08-15 22:19:40

如果将其编写为 self.votes.create!(options) ,调试起来会更容易,因为这样它会抛出带有错误消息的异常。一旦解决了问题,您就可以将其删除,但是您应该考虑如果它不起作用,您的方法应该返回什么。

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

也许你应该将其重写为:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文