Rails将视图设置为在before_filter中呈现

时间:2015-04-07 02:56:04

标签: ruby-on-rails rendering

是否可以设置要从before_filter渲染的视图?

class ProductsController < ApplicationController
  before_filter :set_special_view


  def action1
    # some logic

    # i do not want to call render here
  end

  def action2
    # some logic

    # i do not want to call render here
  end

  private

  def set_special_view
    #self.class.view 'products/v1.html.erb' if some_cond?
    #self.class.view 'products/v2.html.erb' if anoter_cond?


    #self.class.layout :somelayout if some_cond?

  end
end

可以将布局设为

self.class.layout :somelayout if some_cond?

有设置视图的方法吗?所以我在before_filter中设置了视图,我没有触及动作。

2 个答案:

答案 0 :(得分:0)

可以通过覆盖我的控制器中的default_render来完成:

class ProductsController < ApplicationController

before_filter :set_special_view


  def action1
    # some logic

  end

  def action2
    # some logic

  end

  def default_render(*args)
    unless @myview.nil?
      render @myview and return
    end

    super
  end


  private

  def set_special_view
    # decide which view to show here

    @myview = 'products/v1.html.erb' if cond1?
    @myview = 'products/v2.html.erb' if cond2?

  end
end
置于'actionpack / lib / action_controller / metal / implicit_renderer.rb'中的

default_render只调用render而不带参数:

module ActionController
  module ImplicitRender
    def send_action(method, *args)
      ret = super
      default_render unless performed?
      ret
    end

    def default_render(*args)
      render(*args)
    end

    def method_for_action(action_name)
      super || if template_exists?(action_name.to_s, _prefixes)
        "default_render"
      end
    end
  end
end

在我们的default_render中,我们使用视图模板调用render。

查看Rails如何在此处呈现模板 - http://climber2002.github.io/blog/2015/02/21/how-rails-finds-your-templates-part-1/

答案 1 :(得分:-1)

使用and return在渲染后不运行任何逻辑。

def set_special_layout
  #render 'products/v1' and return if some_cond?
  #render 'products/v2' and return if anoter_cond?

  #self.class.layout :somelayout if some_cond?

end