私はこれを理解するために何時間も試みました。支払いモデル payment.rb でこのコードを使用して、支払いを正常に行うことができます。
def save_with_payment
if valid?
customer = Stripe::Customer.create(description: email, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
Stripe::Charge.create(
:amount => (total * 100).to_i, # in cents
:currency => "usd",
:customer => customer.id
)
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
ユーザー モデルのユーザー テーブル属性 customer_id に Stripe の customer.id を保存したいのですが、上記のコードは私の支払いモデルにあります。
Stripe のヘルプ セクションによると、これは次の手順で簡単に実行できます。
save_stripe_customer_id(user, customer.id)
じゃあ後で:
customer_id = get_stripe_customer_id(user)
Stripe::Charge.create(
:amount => 1500, # $15.00 this time
:currency => "usd",
:customer => customer_id
)
save_stripe_customer_id に入れるコードは何ですか? そのコードはどこに置くのですか?Stripeのcustomer.idを生成している上記の方法は支払いモデルにありますが、それをユーザーモデルの属性として保存して、後でユーザーがクレジットカードを再入力することなく請求できるようにしたいと考えています。Payment モデルで生成されたものを users テーブルに保存するにはどうすればよいですか?
編集:
payment.rb
belongs_to :user
user.rb
has_many :payments
ユーザー テーブルに customer_id として追加したい属性は、すでに支払いテーブルに strip_customer_token として含まれています。そこで使用する方法や、ユーザー テーブルに転送する方法がわかりません。
もっと:
payment_controller.rb:
def create
if current_user
@payment = current_user.payments.new(params[:payment])
else
@payment = Payment.new(params[:payment])
end
respond_to do |format|
if @payment.save_with_payment
format.html { redirect_to @payment, notice: 'Payment was successfully created.' }
format.json { render json: @payment, status: :created, location: @payment }
else
format.html { render action: "new" }
format.json { render json: @payment.errors, status: :unprocessable_entity }
end
end
end
その理由は
self.user.update_attribute(customer_id, customer.id)
ユーザーが関与しているため、customer_idの未定義のメソッドを何らかの方法でDeviseに関連させていますか? ルート ファイルで変更する必要があるものはありますか?
ルート.rb
devise_for :users, :path => 'accounts' do
get 'users', :to => 'store#index', :as => :user_root
end
resources :users
resources :payments
match ':controller(/:action(/:id))(.:format)'