Use find to initialize a constant?

前端 未结 3 2047
终归单人心
终归单人心 2021-01-28 09:28

Something like this:

class Category

   SOME_CATEGORY = find_by_name(\"some category\")

end

Category::SOME_CATEGORY
tried wi

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 10:10

    If you don't want to hit the database each time you'll have to cache the model. There are several ways to do this, but one quick way is using Memoization. This was introduced in Rails 2.2.

    class Category < ActiveRecord::Base
      class << self
        extend ActiveSupport::Memoizable
        def named(name)
          find_by_name(name)
        end
        memoize :named
      end
    end
    

    Use it like this.

    Category.named("some category") # hits the database
    Category.named("some category") # doesn't hit the database
    

    The cache should stay persistent across requests. You can reset the cache by passing true as the last parameter.

    Category.named("some category", true) # force hitting the database
    

提交回复
热议问题