【发布时间】:2015-05-25 05:53:08
【问题描述】:
我的代码有问题。当用户单击索引页面上提供的下载链接时,PDF 文件将生成,同时它将使用 Rails 3 下载。我正在使用 prawn gem 生成 PDF .但我不知道rails中link_to标签中的路由路径应该是什么。请检查我下面的代码。
产品/index.html.erb:
<h1>Choose the option</h1>
<p>
<%= link_to "new input",products_new_path %>
</p>
<table>
<tr>
<th>Product name</th>
<th>Product Catagory</th>
</tr>
<% @product.each do |p| %>
<tr>
<td><%= p.p_name %></td>
<td><%= p.p_catagory %></td>
</tr>
<% end %>
</table>
<%= link_to "Download Pdf" %>
控制器/products_controller.rb:
class ProductsController < ApplicationController
def index
@product=Product.all
require "prawn/table"
require "prawn"
Prawn::Document.generate("test.pdf") do |pdf|
table_data = Array.new
table_data << ["Product name", "Product category"]
@product.each do |p|
table_data << [p.p_name, p.p_catagory]
end
pdf.table(table_data, :width => 500, :cell_style => { :inline_format => true })
end
end
def new
@product=Product.new
end
def create
@product=Product.new(params[:product])
if @product.save
flash[:notice]="Data submitted"
flash[:color]="valid"
redirect_to :action => "index"
else
flash[:alert]="Data could not finish"
flash[:color]="invalid"
render 'new'
end
end
end
宝石文件:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
gem 'prawn', '~> 1.3.0'
gem 'prawn-table', '~> 0.2.1'
routes.rb:
Generate::Application.routes.draw do
root :to => "products#index"
get "products/new" => "products#new"
post "products/create" => "products#create"
end
我的要求是当用户点击"Download pdf"链接时,html表值将转换为pdf并生成用于打印和下载。请帮我解决这个问题。
【问题讨论】:
-
您需要有一个控制器操作,使用
send_data或send_file响应PDF 数据。您的link_to将使用与该控制器操作对应的路由。该控制器操作也可能是您想要放置 PDF 生成逻辑的地方。 -
@Jordan:你能在这里说一下我如何应用你的逻辑吗?
标签: ruby pdf ruby-on-rails-3.2 prawn