Ruby on rails 控制器操作运行后但视图渲染前的Rails筛选器挂钩
我有一个spree commerce 2.1.1应用程序(Rails 4.0.0),我想在产品详细信息页面上展示一些“相关产品”。相关产品将只是随机选择与所查看产品具有相同品牌/性别的产品。它正在工作。。。我制作了Ruby on rails 控制器操作运行后但视图渲染前的Rails筛选器挂钩,ruby-on-rails,ruby-on-rails-4,spree,Ruby On Rails,Ruby On Rails 4,Spree,我有一个spree commerce 2.1.1应用程序(Rails 4.0.0),我想在产品详细信息页面上展示一些“相关产品”。相关产品将只是随机选择与所查看产品具有相同品牌/性别的产品。它正在工作。。。我制作了products\u controller\u decorator.rb,它扩展了spree的products\u controller.rb Spree的products\u controller.rb有一个before\u过滤器,用于设置@product: before_filte
products\u controller\u decorator.rb
,它扩展了spree的products\u controller.rb
Spree的products\u controller.rb
有一个before\u过滤器,用于设置@product
:
before_filter :load_product, :only => :show
我自己的decorator有一个方法可以设置相关的产品
before_filter :get_related_products, :only => :show
问题是:
a) 碰巧的是,load\u product
before过滤器在我的get\u related\u products
before过滤器之前被调用,因此顺便说一句,我可以访问它设置的@product
变量。但就我所知,这并不能保证会发生。我想确定我的过滤器稍后会被调用
及
b) Spree的show
方法还设置了@taxon
,我非常希望能够在我自己的获取相关产品的方法中使用它
因此,我想要的是一个类似CakePHP的before_render
的钩子,它在控制器方法运行之后,但在视图渲染之前被调用。我似乎找不到与rails相当的版本。有这样的事吗after\u filter
不会为我执行此操作,因为它是在渲染视图后调用的
如果没有,在Spree的products controller的show
方法运行后,调用获取相关产品的最佳方式是什么,在某种程度上,我可以获取它的实例变量?a)Spree的加载产品将始终在您的获取相关产品之前调用,因为它以前已注册
b) 渲染前没有,过滤前和过滤后之间没有过滤
您可以通过覆盖:render:
class Spree::ProductsController.class_eval do
def render(options = nil, extra_options = {}, &block)
# here you define related products
@related_products = search_related_products(@product)
# don't forget to call super
super(options, extra_options, &block)
end
end
这个答案可能更清晰:def render(*args)在渲染和超级结束之前运行