Ulises
Ulises

Reputation: 416

Rails Model error unknown attribute on save with belongs_to and has_many

I wasn't to understand how the model on Rails works when you setup the relations with plural or non-plural.

Example:

We have this model called "Cliente".

class Cliente < ApplicationRecord
    has_many :sucursales
end

The table on MySQL is:

enter image description here

And we have the model called "Sucursale":

class Sucursale < ApplicationRecord
    belongs_to :cliente
end

The table is:

enter image description here

On the table sucursale already has "clientes_id" that was created with a migration "t.belongs_to :clientes, index: true.

On our simple crud, we want to create a new Sucursale with the client relation with:

def create
        @sucursalcliente = Cliente.find(params[:clientes_id])
        @sucursalcliente.sucursales.build(
            :nombre => params[:nombre], 
            :calle => params[:calle],
            :numero_interior => params[:numero_interior],
            :numero_exterior => params[:numero_exterior],
            :colonia => params[:colonia],
            :municipio => params[:municipio],
            :estado => params[:estado],
            :pais => params[:pais],
            :codigo_postal => params[:codigo_postal],
            :email => params[:email],
            :telefono => params[:telefono]
        )])
        if @sucursalcliente.save
            flash[:info] = 'Sucursal creado correctamente'
            redirect_to action: 'index'
        else
            flash[:alert] = 'Error al crear la sucursal'
            redirect_to action: 'index'
        end
    end

But when we run that script we get.

unknown attribute 'cliente_id' for Sucursale.

Are we missing something?

Upvotes: 2

Views: 1612

Answers (1)

Pavan
Pavan

Reputation: 33542

unknown attribute 'cliente_id' for Sucursale.

The problem is that t.belongs_to :clientes, index: true generates the column name as clientes_id not cliente_id

Solution:

You can choose to rollback the migration, edit the code in the migration file as

t.belongs_to :cliente, index: true

and migrate it again.

OR

If you choose not to rollback the migration, then specify the custom foreign_key on the association to override the default behavior of Rails.

class Cliente < ApplicationRecord
  has_many :sucursales, foreign_key: :clientes_id
end

Upvotes: 2

Related Questions