I've integrated Stripe Tax into my application but I can't get past an error when I try to loop my line items (products) into the code for the Tax Calculation. It DOES NOT give me an error if I do the following and only include one line item.
line_items: [
{
amount: self.subtotal,
reference: 'Products',
},
],
This is the error it gives when I do the code below:
received unknown parameter: v1
I'd like to send all of the line items from the cart the customer is purchasing. I have the syntax wrong or something. I don't think it likes the comma.
line_items: [
@cart.cart_line_items.each do |item|
{
amount: item.subtotal,
reference: item.name,
},
end
],
Any thoughts or advice is appreciated.
I've integrated Stripe Tax into my application but I can't get past an error when I try to loop my line items (products) into the code for the Tax Calculation. It DOES NOT give me an error if I do the following and only include one line item.
line_items: [
{
amount: self.subtotal,
reference: 'Products',
},
],
This is the error it gives when I do the code below:
received unknown parameter: v1
I'd like to send all of the line items from the cart the customer is purchasing. I have the syntax wrong or something. I don't think it likes the comma.
line_items: [
@cart.cart_line_items.each do |item|
{
amount: item.subtotal,
reference: item.name,
},
end
],
Any thoughts or advice is appreciated.
Your issue is with how you're attempting to use .each
inside an array. In Ruby, .each
does not return an array—it just iterates over the items. Instead, you should use .map
, which returns a new array.
line_items: @cart.cart_line_items.map do |item|
{
amount: item.subtotal,
reference: item.name
}
end
What Went Wrong?
Misuse of .each
.each
only iterates and does not return an array.
You need .map
, which transforms and returns a new array.
Syntax Issue
.each
inside an array (line_items: [ @cart.cart_line_items.each do ... end ]
), which results in an unexpected behavior..map
loops through @cart.cart_line_items
and returns an array of hashes, correctly formatting line_items
.
#map
instead of#each
and get rid of the brackets and comma.#each
returns the object it was called on and not the results of the block and should only be used if you just care about the side effects and not the results. This is more a Ruby 101 thing than a Stripe thing. – max Commented Jan 23 at 21:00map
as you suggested. I taught myself Rails so I didn't start with Ruby. I've seenmap
many times of course but never used it until now. Here's what I used in place of the above:line_items: self.cart_line_items.map {|item| {:amount => item.price, :reference => item.product.name}},
. Thanks for the help. – Tony S. Commented Jan 24 at 3:27{ amount: item.price, reference: item.product.name }
. It's more succint and less noise. – max Commented Jan 24 at 9:39