Rails 优化(使用 activerecord 和视图助手)
Rails 有没有办法做到这一点: 我有一个 activerecord 查询
@posts = Post.find_by_id(10)
每当调用查询时,都会生成 SQL 并在数据库中执行,如下所示
SELECT * FROM 'posts' WHERE id = 10
每次执行 AR 查询时都会发生这种情况。类似地,使用这样的辅助方法,
<%= f.textarea :name => 'foo' %>
#=> <input type='textarea' name='foo' />
我编写了一些 Railsy 代码,这些代码生成一些由其他系统(数据库、Web 浏览器)使用的文本。我想知道是否有办法编写 AR 查询或辅助方法调用来生成文件中的文本。这样,文本渲染只完成一次(每次代码更改时),而不是每次调用该方法时?
Is there a way to do this in Rails:
I have an activerecord query
@posts = Post.find_by_id(10)
Anytime the query is called, SQL is generated and executed at the DB that looks like this
SELECT * FROM 'posts' WHERE id = 10
This happens every time the AR query is executed. Similarly with a helper method like this
<%= f.textarea :name => 'foo' %>
#=> <input type='textarea' name='foo' />
I write some Railsy code that generates some text that is used by some other system (database, web browser). I'm wondering if there's a way to write an AR query or a helper method call that generates the text in the file. This way the text rendering is only done once (each time the code changes) instead of each time the method is called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看该行,第一个行可能会访问数据库,但后面的行可能会在行开头显示 CACHE,这意味着它将访问 ActiveRecord 的查询缓存。
在我看来,您想缓存页面,而不是查询。即使它是查询,我也不认为它像
find_by_id(10)
那么简单:)Look at the line, it may be going to the database for the first one but ones after it could be saying CACHE at the start of the line meaning it's going to ActiveRecord's query cache.
It also sounds to me like you want to cache the page, not the query. And even if it were the query, I don't think it's as simple as
find_by_id(10)
:)就像 Radar 建议的那样,您可能应该研究一下 Rails 缓存。您可以从内存存储或文件缓存等简单的东西开始,然后在必要时转向 memcached 等更好的东西。您可以在辅助方法中添加一些缓存,该方法将在查询一次结果后缓存结果。例如,您可以这样做:
剩下要做的唯一一件事是放入一些代码,以便在帖子更改时使缓存条目过期。为此,请看一下在 Rails 中使用“Sweepers”。或者,您可以查看一些缓存宝石,例如 Cache-fu 和 Cached-model。
Like Radar suggested you should probably look into Rails caching. You can start with something simple like the memory store or file cache and then move to something better like memcached if necessary. You can throw in some caching into the helper method which will cache the result after it is queried once. So for example you can do:
The only other thing left to do is put in some code to expire the cache entry if the post changes. For that take a look at using "Sweepers" in Rails. Alternatively you can look at some of the caching gems like Cache-fu and Cached-model.
我不确定我是否完全理解你的问题。
如果您询问生成的查询,并且不想使用活动记录动态方法,则可以执行
find_by_sql
并编写自己的 SQL。如果您询问将结果集缓存到文件中,它已经在数据库中,我不知道如果它在文件中会更有效。
I'm not sure I understand your question fully.
If you're asking about the generated query, you can just do
find_by_sql
and write your own SQL if you don't want to use the active record dynamic methods.If you're asking about caching the resulset to a file, it's already in the database, I don't know that if it was in a file it would be much more efficient.