我正在建立一个会员可以购买视频的视频市场。但是,我正在努力创建订单,以便它具有 video_id、member_id 和价格。这是我的代码:
视频型号:
has_many :members, through: :orders
has_many :orders
accepts_nested_attributes_for :orders
会员型号:
has_many :orders
has_many :videos, through: :orders
accepts_nested_attributes_for :orders
订购型号:
attr_accessible :price, :stripe_card_token, :member_id, :video_id
belongs_to :video
belongs_to :member
accepts_nested_attributes_for :video
accepts_nested_attributes_for :member
validates :member_id, presence: true
validates :video_id, presence: true
validates :price, presence: true
attr_accessor :stripe_card_token
def save_with_stripe
video = @video.find_by_id(params[:id])
member = @member.find_by_id(params[:id])
if valid?
@order = Stripe::Charge.create(
amount: video.price,
currency: "gbp",
card: stripe_card_token,
description: member.email
)
save!
end
rescue
errors.add :base, "There was a problem with Stripe"
end
订单控制器:
def new
@order = Order.new
build_order
end
def create
@order = Order.new(params[:order])
if @order.save_with_stripe
flash[:success] = "Enjoy the video!"
else
render partial: 'shared/buynow'
end
end
def build_order
@order.build_member(
member_id: @member.id,
video_id: @video.id,
price: @video.price,
)
end
我认为我的问题出在“build_order”方法的某个地方,但我尝试了各种不同的方法,最终得到了各种不同的错误。
It works in my console:
[221] pry(main)> Order.create(member_id: "36", video_id: "99", price: "1000")
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO "orders" ("created_at", "member_id", "price", "stripe_card_token", "updated_at", "video_id") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["created_at", Fri, 18 Oct 2013 14:50:09 UTC +00:00], ["member_id", 36], ["price", 1000], ["stripe_card_token", nil], ["updated_at", Fri, 18 Oct 2013 14:50:09 UTC +00:00], ["video_id", 99]]
(0.5ms) COMMIT
=> #<Order id: 3, video_id: 99, member_id: 36, stripe_card_token: nil, price: 1000, created_at: "2013-10-18 14:50:09", updated_at: "2013-10-18 14:50:09">
对我做错的任何帮助将不胜感激。
干杯,马克