0

我正在嘗試實現與Rails的PayPal集成。在此之後(http://railscasts.com/episodes/141-paypal-basics)我有一個模型中的函數,它調用帶返回url的PayPal服務。我添加了一個鏈接來查看鏈接到模型中的方法。但是一些軌道如何無法在模型中獲取函數。Ruby on Rails:在視圖中調用模型方法

我在做什麼錯了?

筆者認爲:

form_for @order do |f| 
- if @order.errors.any? 
    #error_explanation 
     h2 = "#{pluralize(@order.errors.count, "error")} prohibited this order from being saved:" 
     ul 
      - @order.errors.full_messages.each do |message| 
       li = message 
.field 
    = f.label :first_name 
    = f.text_field :first_name 
.field 
    = f.label :last_name 
    = f.text_field :last_name 
.field 
    = f.label :card_number 
    = f.text_field :card_number 
.field 
    = f.label :card_verification, "Card Verification Value (CVV)" 
    = f.text_field :card_verification 
.field 
    = f.label :card_expires_on 
    = f.date_select :card_expires_on, {start_year: Date.today.year, end_year: (Date.today.year+10), add_month_numbers: true, discard_day: true}, {class: "browser-default"} 
.field 
    = link_to 'PayPal', @order.paypal_url(current_user)<= link to model function 
.actions 
    = f.submit 

我的模型:定義下面的函數。

def paypal_url(return_url) 
values = { 
    :business => '[email protected]', 
    :cmd => '_cart', 
    :upload => 1, 
    :return => return_url, 
    :invoice => id 
} 

values.merge!({ 
    "amount_#{1}" => item.unit_price, 
    "item_name_#{1}" => item.product.name, 
    "item_number_#{1}" => item.id, 
    "quantity_#{1}" => item.quantity 
}) 

"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query 

錯誤:

NoMethodError in Orders#new 
Showing C:/Users/Suniljadhav/SourceCode/TrainStation/app/views/orders/_form.html.slim where line #24 raised: 

private method `paypal_url' called for #<Order:0x5e49bf8> 
Trace of template inclusion: app/views/orders/new.html.slim 

Rails.root:C:/用戶/ Suniljadhav /源代碼/ TrainStation

+1

你得到什麼錯誤? – mlovic

+0

@mlovic:編輯我的問題的錯誤。 –

回答

0

看來paypal_url是一個私有方法,你正嘗試從同類之外調用它。

在你的Order類中,你可能有關鍵字private。該關鍵字下面的每個方法都將被聲明爲private(而不是public),如果您嘗試從類外部調用它,則會引發錯誤。私有方法只能在定義它們的類中調用。因此,請嘗試移動paypal_url的定義,使其在您的課程中顯示在private之前。

你可以閱讀更多關於如何工作here,以及它背後的原因here

+0

:偉大的我玩愚蠢應該已經弄明白了我自己。任何方式都非常感謝你的幫助 –