【问题标题】:Raise exception when associations are lazy-loaded in the view当关联在视图中延迟加载时引发异常
【发布时间】:2011-05-05 19:38:46
【问题描述】:

使用熟悉的 Rails 示例关联,其中 Posts 有很多 Comments:

控制器

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

查看

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

cmets 关联在视图中被延迟加载。我想确保在我们渲染视图之前所有数据库查询都发生在控制器中。对于这个例子来说这没什么大不了的,但它应该可以更容易地在更复杂的例子中发现 SQL N+1 查询。

我想看的控制器代码是这样的:

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

一旦我们开始渲染视图,有没有办法防止延迟加载关联?我希望有一种方法可以在关联丢失时引发异常,但仅限一旦我们在视图中。

有没有插件可以做到这一点?

【问题讨论】:

  • 从那以后你找到更好的解决方案了吗?

标签: ruby-on-rails ruby


【解决方案1】:

这是一个几乎可以满足我要求的 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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多