【问题标题】:How to make Rails helper methods available when calling render_to_string to render a template调用 render_to_string 渲染模板时如何使 Rails 辅助方法可用
【发布时间】:2014-01-06 21:16:45
【问题描述】:

我有一个 ActiveMailer 类,在里面我使用 render_to_string 方法发送带有附加 PDF 模板的电子邮件,如下所示:

 def send_sales_order(email_service)
    @email_service = email_service
    @sales_order = SalesOrder.find_by_cid(email_service.order[:id])
    mail(:subject => I18n.t("custom_mailer.sales_order.subject", company_name: "test"), :to => @email_service.recipients) do |format|
      format.html
      format.pdf do
        attachments['purchase_order.pdf'] = WickedPdf.new.pdf_from_string(
          render_to_string('sales_orders/show.pdf.erb', locals: {current_company: @sales_order.company})
        )
      end
    end
  end

在 show.pdf.erb 模板中,我调用了其他地方定义的辅助方法,例如 ApplicationController 中定义的 current_company 方法,如下所示:

    class ApplicationController < ActionController::Base
      helper_method :current_company, :current_role

      def current_company
        return if current_user.nil?
        if session[:current_company_id].blank?
          session[:current_company_id] = current_user.companies.first.id.to_s
        end
        @current_company ||= Company.find(session[:current_company_id])
      end

但是当我使用 render_to_string 方法渲染模板时,这些辅助方法不可用,有没有办法解决这个问题?

谢谢

【问题讨论】:

  • 您找到解决方案了吗?
  • 我正在寻求解决同样的问题

标签: ruby-on-rails


【解决方案1】:

ApplicationController.new.render_to_string 为我工作


【讨论】:

【解决方案2】:

从 Rails 5 开始,您可以使用:

rendered_string = ApplicationController.render(
  template: 'invoice/show',
  assigns: { invoice: invoice }
)

这会在 env 之类的控制器中创建一个类似请求的对象,分配一个可在模板中访问的 @invoice 实例变量。

更多选项请参见此处的文档: http://api.rubyonrails.org/classes/ActionController/Renderer.html#method-i-render

【讨论】:

    【解决方案3】:

    我在墙上敲了几个小时。终于找到了成功的add_template_helper 方法。

    class ApplicationController < ActionController::Base
      add_template_helper ApplicationHelper
      ...
      def foo
        @foo = render_to_string(partial: 'some_file.rb')
      end
    end
    

    这将使来自ApplicationHelper 的所有方法都可用,即使在将render_to_string 与部分一起使用时也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多