views:

73

answers:

2

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

A: 

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.

mckeed
The problem was even sillier than that :) I had tried other field names without success. Looks like my code was OK - but my test was rubbish
steveybaby
A: 

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.

psyho
oh, and I forgot to mention that you should use ActiveRecord's increment_counter method, since it's atomic and concurrency-friendly, so to speak.
psyho
Thanks man - what a silly mistake!
steveybaby
Happened tom me more than once too :)
psyho