"Correct" 如何根据 rails 中的请求创建关系?
"Correct" way to create relations from a request in rails?
示例 post 对控制器的请求:
{
"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
},
....
]
}
采购有多次报销,报销属于采购...
在我的控制器中,我正在做:
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
这达到了预期的效果,但感觉我可以更有效地做到这一点,and/or这不是标准约定。我可以创建所有购买实体而无需执行 each
,但是我需要一些方法来创建报销并将它们 link 到购买 ID
注意:显然 user_id: 1
不会投入生产!入门时的便利。
你可以使用Active Record Nested Attributes,它应该创建关联关系。
对于请求中不存在的自定义参数,您可以在相应模型上添加保存前回调并设置值。
示例 post 对控制器的请求:
{
"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
},
....
]
}
采购有多次报销,报销属于采购...
在我的控制器中,我正在做:
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
这达到了预期的效果,但感觉我可以更有效地做到这一点,and/or这不是标准约定。我可以创建所有购买实体而无需执行 each
,但是我需要一些方法来创建报销并将它们 link 到购买 ID
注意:显然 user_id: 1
不会投入生产!入门时的便利。
你可以使用Active Record Nested Attributes,它应该创建关联关系。
对于请求中不存在的自定义参数,您可以在相应模型上添加保存前回调并设置值。