【问题标题】:Ruby on Rails: Calling Model method in viewRuby on Rails:在视图中调用模型方法
【发布时间】:2016-11-04 01:28:30
【问题描述】:

我正在尝试实现 Paypal 与 Rails 的集成。在此之后 (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/Source Code/TrainStation

【问题讨论】:

  • 你遇到了什么错误?
  • @mlovic :编辑了我的错误问题。

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


【解决方案1】:

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

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

您可以阅读更多关于它是如何工作的here,以及它背后的原因here

【讨论】:

  • :太好了,我当时在玩傻,应该自己想出来的。任何方式都非常感谢您的帮助
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多