Wednesday, 14 August 2013

Cannot Get Counter_Cache to update properly in Padrino (Rails)

Cannot Get Counter_Cache to update properly in Padrino (Rails)

I have a Padrino app I am building where I want to use counter_cache. I am
using ActiveRecord as my ORM. In my Repository model, I want to keep a
count of the number of contributions that are associated with a given
repository. Here are the relevant models:
class Repository < ActiveRecord::Base
has_many :contributions, autosave: true
has_many :users, through: :contributions
validates :full_name, presence: true, uniqueness: true
end
class Contribution < ActiveRecord::Base
belongs_to :user
belongs_to :repository, counter_cache: true
end
class User < ActiveRecord::Base
has_many :contributions
has_many :repositories, through: :contributions
validates :username, presence: true, uniqueness: true
end
The schema is as follows:
create_table "contributions", :force => true do |t|
t.integer "user_id"
t.integer "repository_id"
end
create_table "repositories", :force => true do |t|
t.string "full_name"
t.integer "contributions_count", :default => 0
end
create_table "users", :force => true do |t|
t.string "username"
end
I have created a test in Rspec to check to see that the
contributions_count is updating properly. However, I cannot get it to
pass. Here's the spec:
describe "when a new contribution is created" do
it "updates the counter cache" do
repo = Repository.create(full_name: "sample_repo")
user = User.create(username: "sample_user")
expect {
Contribution.create(user: user, repository: repo)
}.to change {repo.contributions_count }.by(1)
end
end
When I run the spec, I get the following failure:
1) Repository when a new contribution is created updates the counter cache
Failure/Error: expect {
result should have been changed by 1, but was changed by 0
# ./spec/models/repository_spec.rb:43:in `block (3 levels) in <top
(required)>'
I have also tried creating Contributions in the console and it is not
updating the repository counter_cache. I've tried a bunch of stuff, but
can't seem to figure out how to get it to work properly. Any help would be
appreciated. Thanks.

No comments:

Post a Comment