Home > other >  "Correct" way to create relations from a request in rails?
"Correct" way to create relations from a request in rails?

Time:05-22

Sample post request to controller:

{
  "card": 1,
  "cardPot": 6,
  "purchases": [
    {
      "description": "groceries",
      "amount": "40.60",
      "transaction_date": "17/02/2022",
      "statement_reference": "10076608",
      "statement_description": "SAINSBURYS              ",
      "reimbursements": [
        {
          "amount": "19.00",
          "pot": 3
        },
        {
          "amount": "21.60",
          "pot": 7
        },
      ],
      "spread": false
    }, 
    ....
  ]
}

Purchase has many reimbursements, Reimbursement belongs to purchase...

In my controller I'm doing:

  def import
    card_id = params[:card]
    card = CreditCard.find_by(id: card_id)
    pay_to_pot = params[:cardPot]
    purchases = params[:purchases]
    purchases.each do |p|
      purchase_params = p.permit(:description, :amount, :transaction_date, :statement_reference, :statement_description).merge({user_id: 1, credit_card_id: card_id})
      new_purchase = Purchase.create(purchase_params)
      p[:reimbursements].each do |r|
        start_date = p[:start_date] || Date.today
        instalments = p[:spread] ? card.free_months_remaining : 1
        Reimbursement.create({purchase_id: new_purchase.id, instalments: instalments, user_id: 1, pay_to_pot_id: pay_to_pot, pay_from_pot_id: r[:pot], total_amount: p[:amount], start_date: start_date })
      end
    end
  end

This gets the desired effect but it feels like I could be doing this more efficiently, and/or that it's not the standard convention. I could create all of the purchase entities without needing to do an each, but then I would need some way to create the reimbursements and link them to the purchase ids

Note: obviously user_id: 1 isn't going to be in production! Just a convenience while getting started.

CodePudding user response:

You can make use Active Record Nested Attributes, which should create associated relation.

Also for the custom params which are not present in request, you can add a before save callback on the respective model and set the value.

  • Related