从连接表模型更新关联记录
我有一个 has_many :through 关系,通过管理层将玩家与团队联系起来。
我想在团队表上有一个计数器(有点像计数器缓存),它告诉我自本周初以来有多少个新关联。当然,计数器缓存不起作用,因为它始终会提供所有已创建的关联。
我尝试从管理模型中更新相关团队。这永远不会成功。尽管关联团队的增量似乎已保存正常,但在创建关联后,我的计数器仍然为 0。
我还尝试使用观察者。正如我预期的那样,观察员被呼叫,我能够检索团队,但再次没有保存对其的任何更新。
我确信我错过了一些明显的东西! Rails 的实现方式是什么?
我设置了一个 github 来说明问题,运行 rake spec 会失败。
I have a has_many :through relationship associating players to teams THROUGH managements.
I want to have a counter on the teams table (a bit like a counter cache) that tells me how many new associations there have been since the beginning of the week. Of course a counter cache wont work because it will always give all the associations that were ever created.
I've tried updating the associated team from within the managements model. This never succeeds. Even though the increment to the associated team appears to be saved OK, after the association is created my counter is still 0.
I also tried using an observer. The observer got called as I expected, I was able to retrieve the team, but any updates to it, again, were not saved.
I'm sure I'm missing something obvious! What is the rails way to implement this?
I setup a github to illustrate the problem, running rake spec will fail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的规范中:
fanteam_spec.rb
基本上您的观察者更新相同的记录,但不是相同的对象。
In your spec:
fanteam_spec.rb
Basically your observer updates the same record, but not the same object.
我怀疑问题在于您将计数器字段命名为“changes”,它已经是一个 ActiveRecord 方法,用于检查自上次保存以来记录属性的更改。尝试更改该字段的名称并查看您的代码是否有效。
I suspect the problem is that you named the counter field
changes
, which is already an ActiveRecord method for inspecting changes to a record's attributes since the last save. Try changing the name of that field and see if your code works.