Pdf là một trong những định dạng phổ biến hiện nay, với ưu điểm là chất lượng cao và không dễ bị thay đổi font chữ hay bố cục của nội dung. Vì thế pdf thường xuyên được sử dụng để lưu trữ những nội dung sau khi đã hoàn thiện và dùng chúng để trao đổi qua mạng. Trong một số website nhiều tác vụ cũng cần đến việc lưu trữ thành định dạng pdf để thuận tiện cho việc lưu trữ lại của người dùng, vì thế hôm nay mình viết bài viết này để tạo một website đơn giản bằng Ruby on Rails có tích hợp tính năng xuất file pdf từ thông tin của trang web với gem PDFKit !!!
Tạo ứng dụng Rails
Tạo một ứng dụng với tên là invoices (hóa đơn) và thêm 2 models:
1 2 3 4 5 6 | $ rails new invoices -d mysql $ cd invoices $ rails generate model invoice date:date client notes total $ rails generate model line_item description price:float invoice:references |
sau đó thêm một số dữ liệu mẫu vào cơ sở dữ liệu bằng cách thêm vào file db/seeds.rb.
1 2 3 4 5 6 7 8 9 | invoice = Invoice.create( client: 'Tùng Phan', total: 165000, date: Date.new(2020, 2, 17)) LineItem.create([ { invoice_id: invoice.id, description: 'Tuổi trẻ đáng giá bao nhiêu???', price: 96000 }, { invoice_id: invoice.id, description: 'Mắt Biếc (Tái Bản 2019)', price: 69000} ]) |
Chạy lệnh rails db:seed trong terminal để thêm hóa đơn mẫu vào cơ sở dữ liệu.
Tạo controller and view
chạy lệnh rails generate controller Invoices index show
để tạo controllers và views.
app/models/invoice.rb
1 2 3 4 | class Invoice < ApplicationRecord has_many :line_items end |
app/models/line_item.rb
1 2 3 4 | class LineItem < ApplicationRecord belongs_to :invoice end |
app/controllers/invoicescontroller.rb
1 2 3 4 | class InvoicesController < ApplicationController def index @invoices = Invoice.all end |
def show
@invoice = Invoice.find(params
1 2 |