Ruby on rails rails中模型的缓存

Ruby on rails rails中模型的缓存,ruby-on-rails,caching,models,Ruby On Rails,Caching,Models,product.rb has_many :votes belongs_to :product def index @products = Product.all.sort { |m| m.votes.count } end 投票.rb has_many :votes belongs_to :product def index @products = Product.all.sort { |m| m.votes.count } end 每次,我都在索引控制器中使用排序:

product.rb

  has_many :votes
belongs_to :product
def index
  @products = Product.all.sort { |m| m.votes.count }
end
投票.rb

  has_many :votes
belongs_to :product
def index
  @products = Product.all.sort { |m| m.votes.count }
end
每次,我都在索引控制器中使用排序:

索引控制器.rb

  has_many :votes
belongs_to :product
def index
  @products = Product.all.sort { |m| m.votes.count }
end
因此,我认为最好缓存每个产品的投票计数(在
products
表中创建额外的列
votescont

如果是,我可以在vote.rb模型中使用
在保存之前和
在删除之前执行该操作吗

或者最佳实践方法是什么


请给我举几个例子。

我想你在找

:counter\u cache
选项可用于更有效地查找所属对象的数量

以这些模型为例:

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

class Customer < ActiveRecord::Base
  has_many :orders
end
类顺序
通过此声明,Rails将保持缓存值为最新,然后返回该值以响应size方法


尽管在包含
属于
声明的模型上指定了
:counter\u cache
选项,但实际列必须添加到关联模型中。在上述情况下,您需要在
客户
模型

中添加一个名为
订单计数
的列

:counter\u cache
选项可用于更有效地查找所属对象的数量

以这些模型为例:

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

class Customer < ActiveRecord::Base
  has_many :orders
end
类顺序
通过此声明,Rails将保持缓存值为最新,然后返回该值以响应size方法


尽管在包含
属于
声明的模型上指定了
:counter\u cache
选项,但实际列必须添加到关联模型中。在上述情况下,您需要在
客户
模型

中添加一个名为
订单计数
的列

:counter\u cache
选项可用于更有效地查找所属对象的数量

以这些模型为例:

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

class Customer < ActiveRecord::Base
  has_many :orders
end
类顺序
通过此声明,Rails将保持缓存值为最新,然后返回该值以响应size方法


尽管在包含
属于
声明的模型上指定了
:counter\u cache
选项,但实际列必须添加到关联模型中。在上述情况下,您需要在
客户
模型

中添加一个名为
订单计数
的列

:counter\u cache
选项可用于更有效地查找所属对象的数量

以这些模型为例:

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

class Customer < ActiveRecord::Base
  has_many :orders
end
类顺序
通过此声明,Rails将保持缓存值为最新,然后返回该值以响应size方法

尽管在包含
属于
声明的模型上指定了
:counter\u cache
选项,但实际列必须添加到关联模型中。在上述情况下,您需要将名为
orders\u count
的列添加到
Customer
模型中