What is automatically "cached" when the view is rendered?

Let's say we have these two outputs in a view:

@post.user.first_name

current_user.posts.size

      

If the outputs above will be called multiple times in each view, is Rails "smart enough" to hit the database every time?

If the answer is yes, is there any "general rule" about this meaning?

If the answer doesn't match - would it be good practice to store the associated object / objects in its own variable?

+3


source to share


2 answers


ActiveRecord caches queries by default for performance . If you run the AC request in the console multiple times, you will see that the second request is much faster due to the AC cache. So I think this works for queries in a view too.

You can manually cache objects using the Rails Fragment Caching feature .

Fragment caching allows you to wrap a piece of presentation logic in a cache block and served from the cache store when the next request comes in.



There are also Cache Stores for you.

Rails provides a variety of stores for cached data (besides SQL and page caching).

+1


source


Requests for a view are executed in the controller action that renders the view. You will notice that you are defining @post

in your controller action, but you may not be able to see current_user

. This is typically because you are using a development gem and the method defining code current_user

is part of the gem.

Everything you need to render the view must be requested in your controller using ActiveRecord

and in application memory when preparing to render the view. So multiple calls to @post or current_user shouldn't matter.

Sometimes objects are called through associations for presentation, for example. @post.user.name

You will need to prompt the user. This will work, but it is better to split Model-View-Controller into loading users along with messages in the controller. Posting MVC and validating your queries in the controller will also help avoid N + 1 query performance issues. See Rails Active Record Query Eager Load



An example of a user request with their posts.

@post = Post.find(post_params).includes(:user)

      

0


source







All Articles