从连接表模型更新关联记录

发布于 2024-08-17 23:23:22 字数 478 浏览 1 评论 0原文

我有一个 has_many :through 关系,通过管理层将玩家与团队联系起来。

我想在团队表上有一个计数器(有点像计数器缓存),它告诉我自本周初以来有多少个新关联。当然,计数器缓存不起作用,因为它始终会提供所有已创建的关联。

我尝试从管理模型中更新相关团队。这永远不会成功。尽管关联团队的增量似乎已保存正常,但在创建关联后,我的计数器仍然为 0。

我还尝试使用观察者。正如我预期的那样,观察员被呼叫,我能够检索团队,但再次没有保存对其的任何更新。

我确信我错过了一些明显的东西! Rails 的实现方式是什么?

我设置了一个 github 来说明问题,运行 rake spec 会失败。

http://github.com/steveybaby/assoc_problem

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.

http://github.com/steveybaby/assoc_problem

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

爱的十字路口 2024-08-24 23:23:22

在您的规范中:

fanteam_spec.rb

it "should be able to create a fanteam" do
    @fanteam.save
    @fanteam.changes.should be(0)
    @fanteam.should be_valid
    @fanteam.players << Factory.build(:player)

    @fanteam.reload # this is what you are forgetting

    @fanteam.changes.should be(1)
  end

基本上您的观察者更新相同的记录,但不是相同的对象。

In your spec:

fanteam_spec.rb

it "should be able to create a fanteam" do
    @fanteam.save
    @fanteam.changes.should be(0)
    @fanteam.should be_valid
    @fanteam.players << Factory.build(:player)

    @fanteam.reload # this is what you are forgetting

    @fanteam.changes.should be(1)
  end

Basically your observer updates the same record, but not the same object.

屋顶上的小猫咪 2024-08-24 23:23:22

我怀疑问题在于您将计数器字段命名为“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.

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