Src
Src

Reputation: 5482

Caching for model in rails

product.rb

  has_many :votes

vote.rb

belongs_to :product

Every time, i use sorting in my index controller:

index_controller.rb

def index
  @products = Product.all.sort { |m| m.votes.count }
end

So, i think it would be good to cache votes count for each product (create additional column votesCount in products table)?

If yes, can i preform that using before_save and before_delete callbacks in vote.rb model?

Or what is the best practice method?

Give me some examples please.

Upvotes: 0

Views: 70

Answers (1)

Pavan
Pavan

Reputation: 33542

I guess you are looking for counter_cache

The :counter_cache option can be used to make finding the number of belonging objects more efficient

Consider these models:

class Order < ActiveRecord::Base
  belongs_to :customer, counter_cache: true
end

class Customer < ActiveRecord::Base
  has_many :orders
end

With this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method.

Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. In the case above, you would need to add a column named orders_count to the Customer model

Upvotes: 3

Related Questions