gpt4 book ai didi

ruby-on-rails - 当关联在 View 中延迟加载时引发异常

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:20 25 4
gpt4 key购买 nike

使用熟悉的 Rails 示例关联,其中帖子有很多评论:

Controller

...
@posts = Post.find(:all)
...

查看

...
<% @posts.comments.each do |comment| %>
...

评论关联在 View 中延迟加载。我想确保在我们开始渲染 View 之前所有的数据库查询都发生在 Controller 中。对于这个例子来说这不是什么大问题,但它应该可以更容易地在更复杂的例子中发现 SQL N+1 查询。

我想看到的 Controller 代码是这样的:

...
@posts = Post.find(:all, :include => :comments)
...

一旦我们开始呈现 View ,是否有办法防止延迟加载关联?我希望有一种方法可以在缺少关联时引发异常,但仅此而已一旦我们进入 View 。

是否有任何插件可以执行此操作?

最佳答案

这是一个几乎可以做我想做的 hack:

在 config/initializers/prevent_lazy_loading_in_view.rb 中

class LazyLoadingPreventedInViewException < ActionView::TemplateError
def initialize template_error
super(template_error.instance_eval{@template}, template_error.instance_eval{@assigns}, template_error.original_exception)
end
end
class ActionController::Base
def render_with_lazy_load_prevention *args, &block
ActiveRecord::Base.connection.disconnect!
begin
render_without_lazy_load_prevention *args, &block
rescue ActionView::TemplateError => e
if e.message['not connected']
raise LazyLoadingPreventedInViewException.new(e)
else
raise e
end
end
ActiveRecord::Base.connection.reconnect!
end
alias_method_chain :render, :lazy_load_prevention
end

这将在渲染 View 时断开数据库。任何延迟加载尝试都会导致异常,并显示包含“未连接”的消息。我们拦截了这个异常并给它起了一个新名字“LazyLoadingPreventedInViewException”只是让它稍微不那么神秘。

这绝对是一个hack,而且也不是很好。可能会给毫无戒心的开发人员造成很大的困惑。如果我决定保留它,我当然不会在生产中保留它。

关于ruby-on-rails - 当关联在 View 中延迟加载时引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5895442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com