I ran into a strange Ruby on Rails counter_cache problem today. Given the following example models:
We want to ensure that the Poll maintains the total vote count. We also want the PollChoice to maintain the votes for that specific choice. In our controller we might be tempted to add a PollVote through either the Poll or PollChoice association with PollVote, but that's where the problem appears.
It turns out that both of the following approaches will only update the votes_count for one or the other instance, but not both.
Instead, if we create the PollVote directly we will get the desired result of both the Poll and PollChoice having their votes_count updated appropriately.
Strange behavior or expected result?
Update: Another solution is to not assign using the ID, but instead assign using the object itself.
A quick test showed this worked as well. (Thanks Arya A)
Need web application development, maintenance for your existing app, or a third party code review?
Velocity Labs can help.Hire us!