I think is not working because I test it with a real db situation, and always returns the content of db
- Execute the
Rails.cache.fetch
- Modify the database
Execute again the
Rails.cache.fetch
, and here It not should return the new value that I've modified in db. but it happens, not caching is executedclass Translation < ActiveRecord::Base
def self.translate(es_text,locale=I18n.locale) Rails.cache.fetch("#{es_text}/#{locale}", expires_in: 1.month) do trad=self.find_by_es_text(es_text) translated=eval("trad.#{locale}_text") return translated if translated.present? end end
end
The test:
I Execute Translation.translate('Alojamiento','en')
and it returns what finds on DB : "Accomodation"
Then I modify the database table replacing "Accomodation" with "Accomodation---", and commit,...
Come back to Rails, execute the same Translation.translate('Alojamiento','en')
and it returns the new value "Accomodation---"
!!!
But it shouldn't!! isn't it? Because I have put expires_in: 1.month
not in 1.second
Or, Does Rails know when database is modified, and expire cache automatically?
I think the cache is not working, or maybe I'm missing some configuration
Thanks a lot
One way to make "it works" (but I don't like) is moving the
Rails.cache...
code in a method controller, and call a url likewww.app/translate/Alojamiento?locale=en
. In this case it works, but caching in a model is more correct.class ApplicationController < ActionController::Base ... def translate text_return=Rails.cache.fetch("#{params[:es_text]}/#{params[:locale]}", expires_in: 1.month) do Translation.translate(params[:es_text],params[:locale]) end render text: text_to_return end
The solution is in put the cache result in a variable, and return it
IT seems is not the same, this:
than this:
But I don't understand why