【问题标题】:Question regarding the creation of an credit_card object on Ryan bates Active_Merchant intergration video关于在 Ryan bates Active_Merchant 集成视频上创建 credit_card 对象的问题
【发布时间】:2010-12-14 10:14:18
【问题描述】:

我正在浏览 Ryan Bates 关于 Active Merchant 集成视频 Railscast #145 的视频,我的问题是关于创建他在 Order.rb 方法中定义的 @credit_card 方法。

def credit_card
  @credit_card||=ActiveMerchant::Billing::CreditCard.new(
    :type=>card_type,
    :number=>card_number,
    :verification_value=>card_verification,
    :month=>card_expires_on.month,
    :year=>card_expires_on.year,
    :first_name=>first_name,
    :last_name=>last_name
  )

结束

我没有关注的是这个方法是如何被调用的。新方法中的 form_for 创建了一个 @order 对象,而没有提及 credit_card 方法。如何调用 credit_card 方法来启动 @credit_card 对象的创建。

我知道虚拟属性,但我不知道实际上是如何调用 credit_card 方法的。

【问题讨论】:

  • 我想我刚刚想通了。对此感到抱歉。

标签: ruby-on-rails paypal activemerchant


【解决方案1】:

查看截屏代码here

在 app/views/orders/new.html.erb

我们可以看到订单,从第一行开始

<% form_for @order do |f| %>

我们看到,在提交时,表单使用了 oders_controller create 方法。

在 app/controller/orders_controller.rb 中

    def create
      @order = current_cart.build_order(params[:order])
      @order.ip_address = request.remote_ip

      if @order.save
        if @order.purchase
          render :action => "success"
        else
          render :action => "failure"
        end
      else
        render :action => 'new'
      end
    end

我们可以看到@order 是从购物车构建的 Order 实例。这里没什么特别的 这个订单现在用@order.save 保存,然后在@order 上调用购买方法

我们来看看这种购买方式吧!

在 app/model/order.rb 中

    def purchase
      response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options)
      transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response)
      cart.update_attribute(:purchased_at, Time.now) if response.success?
      response.success?
    end

第二行response = GATEWAY.purchase(price_in_cents, credit_card, purchase_options) 。 credit_card 方法在那里作为 GATEWAY.purchase 的参数调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2012-02-01
    • 2019-02-10
    • 1970-01-01
    • 2021-05-10
    • 2016-04-06
    • 2015-10-15
    相关资源
    最近更新 更多