1

so im passing a post method on the "charge" method i have but i keep getting 400 bad request.

This is the route and the input json:

POST http://localhost:3000/users/:user_id/accounts/:account_id/credit_card/:credit_card_id/charge'
Content-Type: application/json

{
"created": "8526798985", 
"amount": "2000",
"currency": "usd",
}

And this is the charge method:

  def charge
    transaction = Transaction.new(transaction_params)  
    transaction.credit_card_id = @credit_card.id
    if transaction.valid?
      transaction.save
      new_transaction = { id: transaction.id, created: transaction.created, status: transaction.status, amount: transaction.amount.to_i, currency: transaction.currency, credit_card_id: transaction.credit_card_id }
      render json: new_transaction
    else
      error_json = { error: "Invalid inputs" }
      render json: error_json, status: 400
    end
  end

also this is the transaction_params method

  def transaction_params
  params.require(:transaction).permit(:created, :amount, :currency)
  end

The error

Error occurred while parsing request parameters.
Contents:

{
"created": "8526798985",
"amount": "2000",
"currency": "usd",
}

What am i missing here? I did another api and this worked fine

2
  • 1
    Your JSON does not have the transaction node required as a wrapper per your transaction_params Commented Jan 11, 2021 at 19:25
  • 1
    You should use if transaction.save instead of .valid? as the later does not ensure that the record was actually saved. Commented Jan 11, 2021 at 19:49

1 Answer 1

1

Your strong params is expecting:

{
  "transaction: {
    {
      "created": "8526798985", 
      "amount": "2000",
      "currency": "usd",
    }
  }
}

But you are providing it:

{
  "created": "8526798985", 
  "amount": "2000",
  "currency": "usd",
}

One solution would be to change the way the request body is put together on your front end, or you can update your transaction_params to read:

def transaction_params
  params.permit(:created, :amount, :currency)
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.