0

We have a Rails 5.2 code that have this structure: Contract -> Client -> Account Contract have a Client Client have a Account Contract have the Client Account to.

When we save in the Contract Controller we get and error that ask for the Contract ID on the Account Model.

All the forms are using nested into nested, nested attributed is ok.

/contratos_controller.rb

class ContratosController < ApplicationController
layout "contratouxs"

def new
    @contrato = Contrato.new
    @produtos = Produto.all  
    cliente = @contrato.build_cliente
    cliente.build_logradouro
    cliente.build_contabanco

end

def create
    @contratoux = Contrato.new(contratoux_params)


respond_to do |format|
  if @contratoux.save

        $k = @contratoux.vencimento.to_i  
        $n = (1..@contratoux.produto.parcelas)
        $n.each{|n| 
        @fin = Financeiro.create(contrato_id: @contratoux.id, parcela: n, valor: @contratoux.produto.valor1, data: Date.new(2018, 12, $k).next_month(n)) 
        @fin.save!
          }

      format.html { redirect_to contratouxs_final_path, notice: 'Contrato foi criado com sucesso.' }
      format.json { render :show, status: :created, location: contratouxs_path }
  else
      @contratoux.errors.full_messages  
    format.html { redirect_to contratouxs_path, alert: 'Contrato não foi criado com sucesso.' }
      format.json { render json: @contratoux.errors, status: :unprocessable_entity }
    end
  end
end

def geracontrato
  @contrato = Contrato.last
  respond_to do |format|
        format.pdf { render template: 'contratouxs/contratoux', pdf: 'Contrato'}
  end    

end
def final
end

 private
# Use callbacks to share common setup or constraints between actions.
# def set_contrato
#  @contrato = Contrato.find(params[:id])
# end

# Never trust parameters from the scary internet, only allow the white list through.
def contrato_params
  params.require(:contrato).permit(:valor, :data, :resalva, :termosguarda, :assinaturaeletronica, :datainicio, :datafim, :periodo, :multiplicador, :quantdias, :tiposeguro, :categoriaclausulas, :quantproduto, :revendedor_id, :agente_id, :cliente_id, :produto_id, :user_id, :status ,:vencimento, :cliente, cliente_attributes: [:nome, :tel1, :email1, :tax, :nascimento, :profissao, :faixarenda, :expostapolicamente, :revendedor_id, :agente_id, logradouro_attributes: [:cep, :endereco, :numero, :bairro, :cidade, :uf], contabanco_attributes: [:banco, :conta, :digitoconta, :agencia, :digitoagencia, :revendedor_id, :agente_id, :cliente_id, :contrato_id]])
end

end

Model /contrato.rb

class Contrato < ApplicationRecord
  belongs_to :revendedor
  belongs_to :agente
  belongs_to :cliente
  belongs_to :produto
  belongs_to :user

  has_many :financeiros

  has_one :contabanco    

  accepts_nested_attributes_for :cliente
end

Model /cliente.rb

class Cliente < ApplicationRecord
  belongs_to :agente, optional: true
  belongs_to :revendedor, optional: true
  belongs_to :user, optional: true

  has_one :logradouro, dependent: :destroy     

  has_one_attached :image

  has_many :contratos
  has_one :contabanco

  validates :nome, :tel1, :email1, presence: true
  accepts_nested_attributes_for :logradouro
  accepts_nested_attributes_for :contabanco
 end 

Model /contabanco.rb (is the Account Model)

class Contabanco < ApplicationRecord
  belongs_to :revendedor
  belongs_to :agente
  belongs_to :cliente
  belongs_to :contrato
end

The view form /_form.html.erb

 <%= form_with(model: contratoux, url: contratouxs_path, local: true, id: "form-cliente") do |form| %>
....
   <%= form.fields_for :cliente do |cli| %>
      <%= cli.fields_for :contabanco do |conta| %> 
....
      <% end %>
   <% end %>
 <% end %>

When we save (or save!) the Rails error ask for the Contrato ID ActiveRecord::RecordInvalid in ContratosController#create

The validation fail: Cliente contabanco contrato is need

AleSB
  • 161
  • 1
  • 3
  • You seem to have a few things backwards here. `Contrato` belongs to the `Cleinte` so the `Contracto` cannot create the `Cleinte` and cannot accept nested attributes for the `Cleinte`. The `Cleinte` should create the `Contrato` – engineersmnky Dec 21 '18 at 21:46

1 Answers1

0

Rails has a keyword, autosave, which you can use on your belongs_to relationships. This should solve most of this for you.

Here is an answer to another question which explains this nicely. https://stackoverflow.com/a/38068935/1146473

ekampp
  • 1,904
  • 18
  • 31