如何在调用render_to_string渲染模板时使Rails助手方法可用

12

我有一个 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方法渲染模板时,这些辅助方法不可用,有什么解决办法吗?
谢谢。

1
你找到解决方案了吗? - edymerchk
3
我希望你能翻译成中文:"我正在寻找解决相同的问题。" - Natus Drew
3个回答

7

ApplicationController.new.render_to_string 对我有用



我遇到了一些奇怪的与会话相关的错误。有没有其他选择? - fatuhoku
请看我在这里的回答:https://dev59.com/OF4c5IYBdhLWcg3wFW6N#33349408,作为一个可能的替代方案。 - cweston

0

-2
刚刚在这个问题上撞了几个小时的墙。最终找到了解决方法,那就是使用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时也是如此。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接