使用条纹按钮渲染部分 - 未定义的方法`[]'为零:NilClass

时间:2015-09-03 17:01:22

标签: ruby-on-rails

我正在尝试在注册#edit中呈现Stripe按钮,但实例变量stripe_btn_data返回nil。我不确定发生了什么:

此处 registrations / edit.html.erb (设计)中的部分召唤

<%= render partial: 'charges/premium_button', locals: { stripe_btn_data: @stripe_btn_data } %>

charge / _premium_button.html.erb 中的部分内容

<% if ! stripe_btn_data.nil? %>
    <p><code>stripe_btn_data</code> is nil</p>
<% else %>
   <%= form_tag charges_path do %>
      <h5>Upgrade your account!</h5>
      <script class='stripe-button'
          src="https://checkout.stripe.com/checkout.js"
          data-key="<%= stripe_btn_data[:key] %>"
          data-amount=<%= stripe_btn_data[:amount] %>
          data-description="<%= stripe_btn_data[:description] %>" >
      </script>
  <% end %>
<% end %>

最后我的ChargesController

class ChargesController < ApplicationController

  before_filter :authenticate_user!

  class Amount
    def self.default
      @amount = 10_00
    end
  end

  def new
    @stripe_btn_data = {
        key: "#{ Rails.configuration.stripe[:publishable_key] }",
        description: "Premium Membership - #{current_user.username}",
        amount: Amount.default
    }
  end

  def create
    customer = Stripe::Customer.create(
        email: current_user.email,
        card: params[:stripeToken]
    )

    charge = Stripe::Charge.create(
        customer: customer.id, # Note -- this is NOT the user_id in your app
        amount: Amount.default,
        description: "Premium Membership - #{current_user.email}",
        currency: 'usd'
    )

    flash[:notice] = "Thanks for all the money, #{current_user.email}! Feel free to pay me again."
    redirect_to user_path(current_user)

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

end

Here's the error page

任何帮助都将不胜感激。

解决方案

我创建了RegistrationsController,因为我必须覆盖Devise的默认设置并添加了edit操作。

class RegistrationsController < Devise::RegistrationsController
  def edit
    @amount = 10_00

    @stripe_btn_data = {
        key: "#{ Rails.configuration.stripe[:publishable_key] }",
        description: "Premium Membership - #{current_user.username}",
        amount: @amount
    }
  end
end

最后,我编辑了 routes.rb 文件,告诉Devise使用新的RegistrationsController

devise_for :users, :controllers => {:registrations => "registrations"}

1 个答案:

答案 0 :(得分:1)

您粘贴了ChargesController,但是您应该粘贴RegistrationsController,因为它会呈现部分edit方法。