I have one problem with Ruby on Rails 4, Method create and Strong Parameters, when sending a post with nested values, my app save the object father correct, but the children save only create_at and update_at, below my code:
My JSON sending
{ "CliRazao"=>"FORNECEDOR 1.", "CliCNPJ"=>"78456896000185", "CliEmail"=>"[email protected]", "CliObs"=>"Teste\nTeste\nTEste", "enderecos"=>[ { "EndCEP"=>"17456789", "EndTipo"=>"E", "EndLogradouro"=>"RUA DOS TUCUNARES", "EndNumero"=>"78", "EndBairro"=>"JARDIM AQUARIUS", "EndCidade"=>"MARILIA", "EndEstado"=>"SP" }, { "EndCEP"=>"18456123", "EndTipo"=>"C", "EndLogradouro"=>"RUA AFONSO PENA", "EndNumero"=>"78", "EndBairro"=>"JARDIM NOVO MUNDO", "EndCidade"=>"MARILIA", "EndEstado"=>"SP" } ], "CliERP"=>"C-00125", "cliente"=> { "CliERP"=>"C-00125", "CliRazao"=>"FORNECEDOR 1", "CliCNPJ"=>"78456896000185", "CliEmail"=>"[email protected]", "CliObs"=>"Teste\nTeste\nTEste" }
}
My Model cliente.rb (Father)
class Cliente < ActiveRecord::Base has_many :enderecos, autosave: true
accepts_nested_attributes_for :enderecos
end
My Model endereco.rb (Child)
class Endereco < ActiveRecord::Base belongs_to :cliente end
My controller
class ClientesController < ApplicationController def index @clientes = Cliente.all end
def findById @clientes = Cliente.find(params[:id]); end def create @cliente = Cliente.new(cliente_params); @cliente.enderecos.build(cliente_params[:enderecos_attributes]); logger.debug "Enderecos => #{cliente_params}" respond_to do |format| if @cliente.save format.json { render :show, status: :created } else format.json { render json: @cliente.errors, status: :unprocessable_entity } end end end def update end private def cliente_params params.require(:cliente).permit(:CliERP, :CliRazao, :CliCNPJ, :CliEmail, :CliObs, enderecos_attributes: [:EndTipo, :EndLogradouro, :EndNumero, :EndBairro, :EndCidade, :EndCEP, :EndEstado]) end
end
The enderecos are not inserted in my database and no exception is thrown.
Thanks!
"enderecos" => ....
it should be"enderecos_attributes"=>....
. – Зелёный