Reputation: 267010
I have 2 models:
class Products < ActiveRecord::Base
has_many :purchases
class Purchase < ActiveRecord::Base
belongs_to :Product
The products model has a column purchase_count
I want a very fast efficient way to update this counter that basically runs this sql:
UPDATE products SET purchase_count = (SELECT COUNT(*) from purchases where active=1 and product_id = 123) where id = 123
Can I do this with ActiveRecord ? If not, how can I do this with just raw sql?
Upvotes: 0
Views: 438
Reputation: 11915
You should probably use a counter_cache
column to make it efficient. Rails allows you to set a counter_cache
option to true
in the belongs_to
model(purchase
). But you should generate a migration to add a column to products
table.
For more, look for counter_cache
in http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference
If you just don't want to count all the associated objects and instead need a condition to be passed in, you need a custom counter cache
. Have a look at http://douglasfshearer.com/2006/10/06/custom-counter-cache-with-conditions.html for an example.
Upvotes: 2