I'm using Rails 5. I have the following model
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
Through some crafty debugging, I figured out that the "save" method causes this query to be executed ...
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'
This heppens each time the above method gets called. this is not optimal becaues I have set up my DistanceUnit model to have a cache. Below is its code. How do I get my "save" method to automatically make use of the cache instead of executing this query every time?
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
all
will ignore all newly saved items. – Cysticercus