Rails 4 wicked_pdf在模型中的服务器上保存pdf

Sta*_*ire 5 pdf ruby-on-rails wicked-pdf

我想在这样的模型中保存pdf:

def save_invoice
    pdf = WickedPdf.new.pdf_from_string(
        render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
    )
    save_path = Rails.root.join('pdfs','filename.pdf')
    File.open(save_path, 'wb') do |file|
      file << pdf
    end
  end
Run Code Online (Sandbox Code Playgroud)

保存我的Payment对象后,我在payment.rb模型中完成了.

得到一个错误:

undefined method `render_to_string' for <Payment object>
Run Code Online (Sandbox Code Playgroud)

之前它在控制器中没有问题

def show
    @user = @payment.user
    #sprawdza czy faktura nalezy do danego uzytkownika
    # [nie mozna podejrzec po wpisaniu id dowolnej faktury]
    if current_user != @user
      flash[:error] = I18n.t 'errors.invoice_forbidden'
      redirect_to '/' and return
    end
    respond_to do |format|
      format.html do
        render :layout => false
      end
      format.pdf do
        render :pdf => "invoice",:template => "payments/show"
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

payments/show.pdf.erb当然有一个观点.

Uni*_*key 18

Rails模型没有这种方法render_to_string.渲染视图不是模型的责任.

如果您绝对需要在模型中执行此操作,则可以执行以下操作:

def save_invoice
  # instantiate an ActionView object
  view = ActionView::Base.new(ActionController::Base.view_paths, {})
  # include helpers and routes
  view.extend(ApplicationHelper)
  view.extend(Rails.application.routes.url_helpers)
  pdf = WickedPdf.new.pdf_from_string(
     view.render_to_string(
       :pdf => "invoice",
       :template => 'documents/show.pdf.erb',
       :locals => { '@invoice' => @invoice }
     )
  )
  save_path = Rails.root.join('pdfs','filename.pdf')
  File.open(save_path, 'wb') do |file|
    file << pdf
  end
end
Run Code Online (Sandbox Code Playgroud)

我可能会创建一个这样的服务对象,而不是用所有这些来污染我的模型:

class InvoicePdfGenerator
  def initialize(invoice)
    @invoice = invoice
    @view = ActionView::Base.new(ActionController::Base.view_paths, {})
    @view.extend(ApplicationHelper)
    @view.extend(Rails.application.routes.url_helpers)
    @save_path = Rails.root.join('pdfs','filename.pdf')
  end

  def save
    File.open(@save_path, 'wb') do |file|
      file << rendered_pdf
    end
  end

  private

  def rendered_pdf
    WickedPdf.new.pdf_from_string(
      rendered_view
    )
  end

  def rendered_view
    @view.render_to_string(
      :pdf => "invoice",
      :template => 'documents/show.pdf.erb',
      :locals => { '@invoice' => @invoice }
    )
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在模型中你可以这样做:

def save_invoice
  InvoicePdfGenerator.new(self).save
end
Run Code Online (Sandbox Code Playgroud)

  • 在我的 Rails (4.2) 中,render_to_string 被提取到 ActionController::Rendering 中。所以我必须 view.extend(ActionController::Rendering) 才能获得该方法。 (2认同)
  • 我不得不使用AbstractController :: Rendering而不是ActionController. (2认同)