Omar Omar - 27 days ago 7
Ruby Question

Creating PDFs from scratch on Rails

I was working on creating a pdf receipts on my simple application. I was able to make it work for a generic/mostly hard coded entries. However, when I want the pdf to print out the amounts for a specfic charge (that is not Hard Coded) I get this error on my charges_controller.rb file - "undefined local variable or method `amount' for #" I have listed below my specific github as well the relevant below. Thank you so much for your help guys :)

Exact Error Message:

uninitialized constant Charge::Amount
app/models/charge.rb:18:in

receipt'
app/controllers/charges_controller.rb:64:in
block (2 levels) in show'
app/controllers/charges_controller.rb:60:in `show'

Github - https://github.com/OmarZV/PDF

charges_controller.rb

class ChargesController < ApplicationController
before_action :authenticate_user!
before_action :set_charge, only: [:show]
def index
@charges = Charge.all
end
def new
@charge = Charge.new
end
def create
@charge = Charge.new(charge_params)
respond_to do |format|
if @charge.save
format.html { redirect_to @charge, notice: 'Charge was successfully created.' }
format.json { render :show, status: :created, location: @charge }
else
format.html { render :new }
format.json { render json: @charge.errors, status: :unprocessable_entity }
end
end
end
def show
respond_to do |format|
format.html
format.json
format.pdf {
send_data @charge.receipt.render,
filename: "#{@charge.created_at.strftime("%Y-%m-%d")}-gorails-receipt.pdf",
type: "application/pdf",
disposition: :inline
}
end
end
private
def set_charge
@charge = current_user.charges.find(params[:id])
end
end


charge.rb when it works

class Charge < ApplicationRecord
belongs_to :user
def receipt
Receipts::Receipt.new(
id: id,
product: "GoRails",
company: {
name: "One Month, Inc.",
address: "37 Great Jones\nFloor 2\nNew York City, NY 10012",
email: "teachers@onemonth.com",

},
line_items: [
["Date", created_at.to_s],
["Account Billed", "(#{user.email})"],
["Product", "GoRails"],
["Amount", "Amount"],
["Charged to", "{Card_type}"],

]
)
end
end


charge.rb when it doesn't works

class Charge < ApplicationRecord
belongs_to :user
def receipt
Receipts::Receipt.new(
id: id,
product: "GoRails",
company: {
name: "One Month, Inc.",
address: "37 Great Jones\nFloor 2\nNew York City, NY 10012",
email: "teachers@onemonth.com",

},
line_items: [
["Date", created_at.to_s],
["Account Billed", "(#{user.email})"],
["Product", "GoRails"],
["Amount", "$#{Amount / 100}.00"],
["Charged to", "#{Card_type} (**** **** **** #{Card_last4})"],

]
)
end
end


user.rb

class User < ApplicationRecord
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable
has_many :charges
end

Answer

You've got a capital Amount in your model which will reference a constant. It should be lowercase amount to use the attribute on the charge record instead.

I think that should be: ["Amount", "$#{amount / 100}.00"]