I'm doing a procedure to store the cache in a query to the database in rails, but when I try to test the functionality in the console it does not work for me. It does not save the record in the cache.
I'm using
- Rails 5.2.2
- ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
Query the post database
class PostsSearchService
def self.search(curr_posts, query)
posts_ids = Rails.cache.fetch("posts_search/#{query}", expires_in: 1.hours) do
curr_posts.where("title like '%#{query}%'").map(&:id)
end
curr_posts.where(id: posts_ids)
end
end
Query in the console rails
PostsSearchService.search(Post.all, "lorem")
Result of the console
Running via Spring preloader in process 12312
Loading development environment (Rails 5.2.2)
irb(main):001:0> PostSearchService.search(Post.all, "lorem")
Traceback (most recent call last):
1: from (irb):1
NameError (uninitialized constant PostSearchService)
irb(main):002:0> PostsSearchService.search(Post.all, "lorem")
Post Load (0.5ms) SELECT "posts".* FROM "posts" WHERE (title like '%lorem%')
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 18], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Post id: 18, title: "In doloremque ducimus sint.", content: "Accusamus dolores ab. Beatae accusamus eos. Omnis ...", published: false, user_id: 2, created_at: "2019-01-04 06:42:20", updated_at: "2019-01-04 06:42:20">]>
irb(main):003:0> PostsSearchService.search(Post.all, "lorem")
Post Load (0.6ms) SELECT "posts".* FROM "posts" WHERE (title like '%lorem%')
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 18], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Post id: 18, title: "In doloremque ducimus sint.", content: "Accusamus dolores ab. Beatae accusamus eos. Omnis ...", published: false, user_id: 2, created_at: "2019-01-04 06:42:20", updated_at: "2019-01-04 06:42:20">]>
My doubts:
- How do I activate the cache in the development environment?
- According to guides.rubyonrails.org I should use
rails dev:cache
, but it still does not work.
- According to guides.rubyonrails.org I should use
- Check the configuration of my ../config/environments/development.rb file and it seems normal, except when I use the recommendation of guides.rubyonrails.org I get the following error.
-
config/environments/development.rb:21:in
block in ': undefined methodmegabytes' for 64:Integer (NoMethodError)
-
- How do I prove that rails are writing in the cache?
Thank you in advance for the help you can give me