Skip to content

Instantly share code, notes, and snippets.

@hooopo
Created August 3, 2012 06:12
Show Gist options
  • Save hooopo/3244982 to your computer and use it in GitHub Desktop.
Save hooopo/3244982 to your computer and use it in GitHub Desktop.
fetch_by_name
# -*- encoding : utf-8 -*-
module FetchByName
def fetch_by_name(name, field_name = :name)
if id = Rails.cache.read("cached_#{self.name}_#{field_name}_#{name}")
self.find(id)
else
record = self.where(field_name => name).first || raise(ActiveRecord::RecordNotFound)
record.tap{|record| Rails.cache.write("cached_#{self.name}_#{field_name}_#{name}", record.id)}
end
end
end
class User < ActiveRecord::Base
extend FetchByName
end
class Tag < ActiveRecord::Base
extend FetchByName
end
[3] pry(main)> User.fetch_by_name("hooopo")
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'hooopo' LIMIT 1 #第一次正常的SQL
[4] pry(main)> User.fetch_by_name("hooopo")
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1 # 第二次会用主键查询
[5] pry(main)> User.fetch_by_name("hooopo") # 由于用了https://github.com/csdn-dev/second_level_cache,第二次以后不会去读数据库
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment