- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个模型类 page.rb:
class Page < ActiveRecord::Base
def paypal_url(return_url)
values = {
:business => 'seller_1229899173_biz@railscasts.com',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => id
}
line_items.each_with_index do |item, index|
values.merge!({
"amount_#{index+1}" => item.unit_price,
"item_name_#{index+1}" => item.product.name,
"item_number_#{index+1}" => item.id,
"quantity_#{index+1}" => item.quantity
})
end
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
end
end
在我的 Controller 中:
def order_form
if params[:commit] == "Proceed to Checkout"
redirect_to(@cart.paypal_url("/pages/order_online"))
end
但是当我点击“Proceed to Checkout”时,出现错误:
undefined method `paypal_url' for nil:NilClass
知道我是否遗漏了什么或做错了什么吗?
谢谢!
最佳答案
简单的答案是您的 @cart
变量没有填充任何数据
解决此问题的方法是在您的 order_form
Controller 中创建一个 @cart
变量,如下所示:
def order_form
@cart = Cart.new cart_params #-> how to define your cart var?
redirect_to @cart.paypal_url "/pages/order_online"
end
我查看了 Railscast你一直在使用,他似乎在继续另一集,他解释了如何使用标准 ActiveRecord
更长的答案是,我认为您的系统存在缺陷,因为您在 Page
模型中调用了 PayPal
方法(为什么?)
我们之前已经在 Rails 中设置了自己的购物车(您可以 see here ):
- Cart
session model
#-> stores product id's in a cart modelProduct
model stores the products & links with cartid
'sOrder
controller sends data to Paypal & handles returns
这是给你的一些代码:
#config/routes.rb
get 'cart' => 'cart#index', :as => 'cart_index'
post 'cart/add/:id' => 'cart#add', :as => 'cart_add'
delete 'cart/remove(/:id(/:all))' => 'cart#delete', :as => 'cart_delete'
get 'checkout/paypal' => 'orders#paypal_express', :as => 'checkout'
get 'checkout/paypal/go' => 'orders#create_payment', :as => 'go_paypal'
get 'checkout/stripe' => 'orders#stripe', :as => 'stripe'
#app/models/cart_session.rb #-> "session based model"
class CartSession
#Initalize Cart Session
def initialize(session)
@session = session
@session[:cart] ||= {}
end
#Cart Count
def cart_count
if (@session[:cart][:products] && @session[:cart][:products] != {})
@session[:cart][:products].count
else
0
end
end
#Cart Contents
def cart_contents
products = @session[:cart][:products]
if (products && products != {})
#Determine Quantities
quantities = Hash[products.uniq.map {|i| [i, products.count(i)]}]
#Get products from DB
products_array = Product.find(products.uniq)
#Create Qty Array
products_new = {}
products_array.each{
|a| products_new[a] = {"qty" => quantities[a.id.to_s]}
}
#Output appended
return products_new
end
end
#Qty & Price Count
def subtotal
products = cart_contents
#Get subtotal of the cart items
subtotal = 0
unless products.blank?
products.each do |a|
subtotal += (a[0]["price"].to_f * a[1]["qty"].to_f)
end
end
return subtotal
end
#Build Hash For ActiveMerchant
def build_order
#Take cart objects & add them to items hash
products = cart_contents
@order = []
products.each do |product|
@order << {name: product[0].name, quantity: product[1]["qty"], amount: (product[0].price * 100).to_i }
end
return @order
end
#Build JSON Requests
def build_json
session = @session[:cart][:products]
json = {:subtotal => self.subtotal.to_f.round(2), :qty => self.cart_count, :items => Hash[session.uniq.map {|i| [i, session.count(i)]}]}
return json
end
end
#app/controllers/cart_controller.rb
# shows cart & allows you to click through to "buy"
class CartController < ApplicationController
include ApplicationHelper
#Index
def index
@items = cart_session.cart_contents
@shipping = Shipping.all
end
#Add
def add
session[:cart] ||={}
products = session[:cart][:products]
#If exists, add new, else create new variable
if (products && products != {})
session[:cart][:products] << params[:id]
else
session[:cart][:products] = Array(params[:id])
end
#Handle the request
respond_to do |format|
format.json { render json: cart_session.build_json }
format.html { redirect_to cart_index_path }
end
end
#Delete
def delete
session[:cart] ||={}
products = session[:cart][:products]
id = params[:id]
all = params[:all]
#Is ID present?
unless id.blank?
unless all.blank?
products.delete(params['id'])
else
products.delete_at(products.index(id) || products.length)
end
else
products.delete
end
#Handle the request
respond_to do |format|
format.json { render json: cart_session.build_json }
format.html { redirect_to cart_index_path }
end
end
end
#app/controllers/orders_controller.rb
#Paypal Express
def paypal_express
response = EXPRESS_GATEWAY.setup_purchase(total,
:items => cart_session.build_order,
:subtotal => subtotal,
:shipping => 50,
:handling => 0,
:tax => 0,
:return_url => url_for(:action => 'create_payment'),
:cancel_return_url => url_for(:controller => 'cart', :action => 'index')
)
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
#Create Paypal Payment
def create_payment
response = express_purchase
#transactions.create!(:action => "purchase", :amount => ((cart_session.subtotal * 100) + 50).to_i, :response => response)
#cart.update_attribute(:purchased_at, Time.now) if response.success?
response.success?
redirect_to cart_index_path
end
#Stripe
def stripe
credit_card = ActiveMerchant::Billing::CreditCard.new(
:number => "4242424242424242",
:month => "12",
:year => "2020",
:verification_value => "411"
)
purchaseOptions = {
:billing_address => {
:name => "Buyer Name",
:address1 => "Buyer Address Line 1",
:city => "Buyer City",
:state => "Buyer State",
:zip => "Buyer Zip Code"
}
}
response = STRIPE_GATEWAY.purchase(total, credit_card, purchaseOptions)
Rails.logger.debug response.inspect
@responder = response
render cart_index_path
end
private
def subtotal
(cart_session.subtotal * 100).to_i
end
def total
((cart_session.subtotal * 100) + 50).to_i
end
def express_purchase
EXPRESS_GATEWAY.purchase(total, express_purchase_options)
end
def express_purchase_options
{
:token => params[:token],
:payer_id => params[:PayerID]
}
end
def express_token=(token)
self[:express_token] = token
if new_record? && !token.blank?
details = EXPRESS_GATEWAY.details_for(token)
self.express_payer_id = details.payer_id
self.first_name = details.params["first_name"]
self.last_name = details.params["last_name"]
end
end
end
关于ruby-on-rails - 未定义方法 `paypal_url' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588255/
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!