mongoid - Which rails ActiveRecord callback to sync with service (stripe) when creating a new record and still properly use errors? -


i have user , stripecustomer model. every user embeds 1 , accepts_nested_attributes_for stripecustomer.

when creating new user, create corresponding stripecustomer , if provide either cc or coupon code, create subscription.

in stripecustomer:

attr_accessible :coupon_id, :stripe_card_token 

what i'd is, if coupon invalid, do:

errors.add :coupon_id, "bad coupon id" 

so normal rails controller patters like:

if @stripe_customer.save .... else .... end 

will work. , able use normal rails field_with_errors stuff handling bad coupon.

so question is, @ active record callback should call stripe::customer.create , save stripe_customer_token?

i had on before_create, because want done if going persist record. strange things valid? , worse, if going create via user, save of user , stripecustomer succeeds if errors.add in before_create callback! think issue save fail if add errors , return false @ before_validation.

that last part i'm not sure if mongoid issue or not.

i move before_validation :on => :create create new stripe::customer if called valid? don't want.

anyway, i'm generically curious best practices model backed or linked record on remote service , how handle errors.

ok here did, split calls stripe 2 callbacks, 1 @ before_validation , 1 before_create (or before_update).

in before_validation, whatever can check uncontrolled inputs (directly user) valid. in stripe case means coupon code check stripe valid , add errors :coupon_code needed.

actually creating/updating customers stripe, wait until before_create/before_update (i use 2 instead of doing before_save because handle these 2 cases differently). if there error then, don't handle exception instead of trying add errors after validation (a) doesn't make sense , (b) sort of works fails prevent saves on nested models (in mongoid anyway, bad , strange).

this way know time persisting, attributes sound. of course still fail i've minimized risk substantially. can things call valid? without worrying creating records stripe didn't want.

in retrospect seems pretty obvious.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -