如何访问rails模型中CoffeeScript中创建的变量

How do I access a variable created in CoffeeScript in my rails model?

本文关键字:CoffeeScript 创建 变量 模型 rails 何访问 访问      更新时间:2023-10-17

我正在rails 4应用程序上使用stripe创建客户帐户。

从本质上讲,我知道我捕获cc信息的coffeescript代码(如下)正在成功地与Stripe通信,因为令牌是为一张卡创建的(一旦创建,我就可以将其打印到屏幕上)。

此外,我的模型中有一个方法可以在Stripe中创建客户对象。它连接并显示在条纹中,当我尝试硬编码信用卡信息(即通过具有预设参数的块)时,卡信息显示在条纹上。

然而,我不知道如何将卡令牌从我的coffescript代码传递到我的模型(或控制器,或任何我真正可以使用它的地方)。如果有人能帮我,或者给我指一些关于它的医生,那将是惊人的!

这是我的coffeescript代码,其中令牌保存为"#subscription_stripe_card_token":

  handleStripeResponse: (status, response) ->
if status == 200
  $('#subscription_stripe_card_token').val(response.id)
  $('#stripe_error').text(response.id)
  $('#new_subscription')[0].submit()
else
  $('#stripe_error').text(response.error.message)
  $('input[type=submit]').attr('disabled', false)

这是我的模型,我试图访问它(未成功)(在save_with_payment方法中,调用Stripe::Customer.create,是我试图传递卡信息的地方):

    class Subscription
  include Mongoid::Document
  belongs_to :user
  field :plan, type: String
  field :stripe_customer_token, type: String
  attr_accessor :stripe_card_token
  def save_with_payment(plan, email, name)
    if valid?
        customer = Stripe::Customer.create(description: name, email: email, plan: plan, card: stripe_card_token)
        write_attribute(:stripe_customer_token, customer.id)
        save!
    end
    rescue Stripe::InvalidRequestError => e
    logger.error "Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end

同样,其他一切都有效。目前,我假设它会传递一个"nil"值,但我不知道如何访问它。

你不能。CoffeeScript(编译为JavaScript)在用户的浏览器中运行。Rails在您的服务器上运行。他们无法访问彼此的状态。

它们之间可以进行的唯一通信形式是客户端启动的HTTP请求。

您需要通过AJAX将您的条纹令牌发送到服务器。