我使用rails 5和grape gem来构建我的应用程序。现在我需要生成一个PDF并使用grape端点发送回响应。我正在使用PDF和wkhtmltopdf-binary生成wicked_pdf。但是我面临着undefined method 'render_to_string'的问题。我尝试了各种方法来解决这个问题。但是找不到任何解决方案。
下面是我的代码片段
API终结点:
module Endpoints
class GeneratePdf < Grape::API
get do
users = User.all # I want this users list in my PDF
pdf = WickedPdf.new.pdf_from_string(render_to_string('users/index.html.erb')) # placed in app/views/users/pdf.html.erb
# some code here for send pdf back to response
end
end
endGemfile:
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'配置>初始化器> mime_types.rb
Mime::Type.register "application/pdf", :pdf发布于 2017-10-31 03:05:13
Grape::API,与典型的Rails控制器不同,没有可以在其上调用的render_to_string方法。您应该能够将其替换为类似如下的内容:
require 'erb'
binding_copy = binding
binding_copy.local_variable_set(users: User.all)
template = File.open(Rails.root.join('app/views/users/index.html.erb))
string = ERB.new(template).result(binding_copy)
pdf = WickedPdf.new.pdf_from_string(string)https://stackoverflow.com/questions/47013792
复制相似问题