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

Ruby on Rails: Calling Model method in view

我正在尝试实现与 rails 的 Paypal 集成。在此之后 (http://railscasts.com/episodes/141-paypal-basics),我在模型中有一个函数,它使用 return url 调用贝宝服务。我添加了一个 link,因为 links 到 model.But 中的方法,有些 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/Source Code/TrainStation

paypal_url 似乎是一个私有方法,您正试图从其 class 外部调用它。

在您的 Order class 中,您可能有关键字 private。该关键字下面的每个方法都将被声明为私有(与 public 相对),如果您尝试从 class 之外调用它,将会抛出错误。私有方法只能从定义它们的 class 中调用。因此,请尝试移动 paypal_url 的定义,使其出现在 class 中的 private 之前。

您可以阅读有关其工作原理的更多信息here, and about the reasons behind it here