我的代码有问题。我需要用户点击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
的Gemfile:
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,它也会生成以便打印和下载。请帮我解决此问题。
答案 0 :(得分:3)
产品/ index.html.erb:
<%= link_to "Download_pdf", download_pdf_path(:format => 'pdf') %>
Gemfile:
gem 'prawn'
gem 'prawn-table'
routes.rb,添加以下路线:
get "products/download_pdf" => "products#download_pdf", :as => 'download_pdf'
捆绑安装。
products_controller.rb
require "prawn"
require "prawn/table"
def download_pdf
@product = Product.all
respond_to do |format|
format.pdf do
pdf = Prawn::Document.new
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 })
send_data pdf.render, filename: 'test.pdf', type: 'application/pdf', :disposition => 'inline'
end
end
end
这将生成您的pdf。