我使用Rails 5.我有以下型號如何讓我的模型,利用我的緩存中保存時?
class MyObject < ActiveRecord::Base
...
belongs_to :distance_unit
...
def save_with_location
transaction do
address = LocationHelper.get_address(location)
if !self.address.nil? && !address.nil?
self.address.update_attributes(address.attributes.except("id", "created_at", "updated_at"))
elsif !address.nil?
address.race = self
address.save
end
# Save the object
save
end
end
通過一些狡猾的調試,我想通了,「保存」方法導致此查詢被執行...
DistanceUnit Load (0.3ms) SELECT "distance_units".* FROM "distance_units" WHERE "distance_units"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/models/my_object.rb:54:in `block in save_with_location'
這heppens上述各方法被調用的時間。這不是最佳的,因爲我已經將我的DistanceUnit模型設置爲具有緩存。以下是它的代碼。如何讓我的「保存」方法自動使用緩存而不是每次都執行此查詢?
class DistanceUnit < ActiveRecord::Base
def self.cached_find_by_id(id)
Rails.cache.fetch("distanceunit-#{id}") do
puts "looking for id: #{id}"
find_by_id(id)
end
end
def self.cached_find_by_abbrev(abbrev)
Rails.cache.fetch("distanceunit-#{abbrev}") do
find_by_abbrev(abbrev)
end
end
def self.cached_all()
Rails.cache.fetch("distanceunit-all") do
all
end
end
end
你是否在開發或生產運行呢? – Iceman
我在開發中運行了上面的測試,但它也在生產中發生。 – Dave
可以包括DISTANCE_UNIT和my_object的關係? –