Ruby on Rails:在视图中调用Model方法

时间:2016-07-01 15:09:46

标签: ruby-on-rails ruby ruby-on-rails-4 paypal ruby-on-rails-4.2

我正在尝试使用rails实现Paypal集成。在此之后(http://railscasts.com/episodes/141-paypal-basics)我在模型中有一个函数,它使用返回URL调用paypal服务。我在视图中添加了一个链接到模型中方法的链接。但是一些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 => 'xxxxx.XXXXX@techflex.com',
  :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:/ Users / Suniljadhav /源代码/ TrainStation

1 个答案:

答案 0 :(得分:0)

似乎paypal_url是一个私有方法,你试图从它的类外部调用它。

Order课程中,您可能拥有关键字private。该关键字下面的每个方法都将被声明为私有(而不是公共),如果您尝试从类外部调用它,则会抛出错误。私有方法只能从定义它们的类中调用。因此,请尝试移动paypal_url的定义,使其显示在您班级的private之前。

您可以详细了解其工作原理here及其背后原因here