Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `with_indifferent_access' for #<Array:

I've tried it in a number of ways but it does not work. I have in this project, another controller with the same code working, the difference that another uses the has_many relationship, and the one with problem is has_one and belongs_to. Let's go to the code.

class Endereco < ActiveRecord::Base
 has_one :user
end

class User < ActiveRecord::Base
 belongs_to :endereco
 accepts_nested_attributes_for :endereco

The strong parameter in controller:

class Backoffice::UsersController < BackofficeController

def create
 @user = User.new(params_user)
 respond_to do |format|  
  if @user.save!
    format.json { render json: @user, include: :endereco}
  else
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
 end
end



 def params_user
   params.require(:user).permit(:nome, 
        :email, 
        :password, 
        :password_confirmation, 
        :cpf, 
        :tel_fixo, 
        :tel_cel,
        endereco_attributes: [
          :rua,
          :bairro,
          :cidade,
          :uf,
          :cep,
          :referencia,
          :numero,
          :complemento          
          ])
  end 

When I send this json via POSTMAN I get the error> undefined method `with_indifferent_access' for #Array: on this line

@user = User.new(params_user)

{   "user":{
    "nome" : "teste1", 
    "email" : "[email protected]", 
    "password": "123", 
    "password_confirmation": "123", 
    "cpf": "123321", 
    "tel_fixo": "123321", 
    "tel_cel": "asdsd",
    "endereco_attributes": [
        {
          "rua": "tt",
          "bairro": "tete",
          "cidade": "asdas",
          "uf":"asdasd",
          "cep": "12321",
          "referencia": "asdasd",
          "numero":"123",
          "complemento":"123" }
    ]
}}

Someone to give me a light? Thank you!

like image 380
Jorge Miguel Avatar asked Nov 04 '17 18:11

Jorge Miguel


2 Answers

You made endereco_attributes in your input an Array, rather than an object (which then becomes a Hash in Ruby). Since it is a singular (belongs_to) association, Rails expects it to be a Hash, not an Array of Hashes. Array does not have the method with_indifferent_access, but Hash does.

Change your input to match the correct structure and all should be well.

like image 118
Andrew Marshall Avatar answered Oct 26 '22 18:10

Andrew Marshall


My json was wrong ... where I was with [] and should not

 "endereco_attributes": [{... }]

correct

  "endereco_attributes": {... }

Thanks.

like image 9
Jorge Miguel Avatar answered Oct 26 '22 20:10

Jorge Miguel