Update parent model when it is nested as the child

0

I am creating a system where the user creates a proposal, in the proposal form he must enter the data of the client that is in a separate table.

This is working to create the proposal, but not to upgrade, because the way I am presenting below, the error "unknown attribute 'offer_value' for Customer" appears. Here is my code:

I have 2 models:

class Sale < ApplicationRecord
    belongs_to :customer, inverse_of: :sales

    accepts_nested_attributes_for :customer
end

class Customer < ApplicationRecord
    has_many :sales, inverse_of: :customer
end

Sale Controller:

class SalesController < ApplicationController
    before_action :authenticate_user!

    def new
        @sale = Sale.new
        @sale.build_customer
    end



    def create
        @sale = Sale.new(proposta_params)

        respond_to do |format|
          if @sale.save
            format.html { redirect_to dashboard_path, notice: 'Proposta criada com sucesso.' }
          else
            format.html { render :new }
            @sale.errors.each do |erro|
                puts erro
            end
          end
        end

    end


    def edit
        @sale = Sale.find(params[:id])
        @sale.customer
    end


    def update
        @sale = Sale.find(params[:id])

        respond_to do |format|
          if @sale.customer.update(proposta_params)

            format.html { redirect_to dashboard_path, notice: 'Proposta alterada com sucesso.' }

          else
            format.html { render :edit }
            @sale.errors.each do |erro|
                puts erro
            end
          end
        end

    end



    private
        def proposta_params
            params.require(:sale).permit(:valor_oferta, :grupo_promocao, :codigo_oferta, :modo_pagamento, :vencimento, :banco, :agencia, :conta, :isento, :valor, :data_envio_qualidade, :data_agendamento_qualidade, :janela_agendamento, :data_instalacao_qualidade,:tv_id, :phone_id, :internet_id, :equipamentos, :cep, :rua, :numero, :complemento, :bairro, :cidade, :uf, :ponto_de_referencia, :obs, customer_attributes: [:name, :cpf_pf, :nascimento_pf, :nome_mae_pf, :nome_mae_pf, :cnpj_pj, :fundacao_pj, :telefone1, :telefone2, :telefone3, :email, :juridica])
        end
end

PS: I have tried to use only "@ sale.update (proposal_params)", but this way it creates another Client instead of updating

The VALUE_OFERTA field is part of SALE and not of Customer.

Could you please help me out?

    
asked by anonymous 03.06.2017 / 20:14

1 answer

0

I found the solution

Instead of @ sale.customer.update (proposal_params) I should use @ sale.update (proposal_params) and also was missing add the "id" of Customer in the customer_attributes of the proposed_params method

    
03.06.2017 / 20:31