如果有人试图弄清楚如何在 Rails 5 属性哈希中添加/编辑嵌套属性,我发现这是最直接(替代)的方法。不要为 merge 或 deep_merge 烦恼……由于参数强大,这很痛苦。在此示例中,我需要在保存之前将 group_id 和 vendor_id 复制到关联的发票(嵌套参数)。
def create
my_params = order_params
@order = Order.new
@order.attributes = my_params
@order.invoice.group_id = my_params[:group_id]
@order.invoice.vendor_id = my_params[:vendor_id]
@order.save
end
private
# Permit like normal
def order_params
params.require(:order).permit([:vendor_id, :group_id, :amount, :shipping,:invoice_attributes => [:invoice_number, :invoice_date, :due_date, :vendor_id, :group_id]])
end