jessesr
jessesr

Reputation: 43

Changing Stripe param keys for mass assignment in Rails

I'm integrating Stripe into a Rails app. Right now Stripe Checkout returns a params hash with key-value pairs like:

"stripeShippingAddressZip"=>"80205"

and

"stripeShippingAddressState"=>"CO"

I also have a method called order_params which calls params.permit to prevent mass assignment vulnerabilities.

I'd like to do the following:

current_user.orders.build(order_params)

Essentially mass assignment.

However, my orders model has attributes like shipping_zip rather than stripeShippingAddressZip.

How can I use the params hash and still do mass assignment given that the hash keys don't match the attributes of the model?

Is there are "Rails way" of doing this?

Upvotes: 0

Views: 54

Answers (1)

aks
aks

Reputation: 9491

There are multiple ways you can do this, but I like to do the mapping like so:

def order_params
  {
    shipping_zip: params[:stripeShippingAddressZip],
    # more here
  }
end

After this you can just do:

Orders.create(order_params)

I hope this helps!

Upvotes: 3

Related Questions