Ruby on rails 在视图中延迟加载关联时引发异常
使用熟悉的Rails示例关联,其中帖子有许多注释: 控制器Ruby on rails 在视图中延迟加载关联时引发异常,ruby-on-rails,ruby,Ruby On Rails,Ruby,使用熟悉的Rails示例关联,其中帖子有许多注释: 控制器 ... @posts = Post.find(:all) ... 查看 ... <% @posts.comments.each do |comment| %> ... 一旦我们开始渲染视图,有没有一种方法可以防止延迟加载关联?我希望有一种方法可以使它在关联丢失时抛出异常,但只有在我们进入视图时才会这样做 有任何插件可以做到这一点吗?这是一种几乎可以满足我要求的黑客行为: 内部配置/initializers/protect
...
@posts = Post.find(:all)
...
查看
...
<% @posts.comments.each do |comment| %>
...
一旦我们开始渲染视图,有没有一种方法可以防止延迟加载关联?我希望有一种方法可以使它在关联丢失时抛出异常,但只有在我们进入视图时才会这样做
有任何插件可以做到这一点吗?这是一种几乎可以满足我要求的黑客行为: 内部配置/initializers/protect_lazy_加载_在_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
类LazyLoadingPreventedViewException这绝对是一个黑客,而且也不是很好。可能会给毫无戒心的开发人员带来很大的混乱。如果我决定保留它,我肯定不会在生产中保留它。从那时起,您找到更好的解决方案了吗?
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