Relationship between two tables with different id

2

I'm trying to make a relationship between the users table and the companies table, the database was previously created outside of rails, so the primary key of companies is "company" and the user "user", the relationship : a company has many users and a user belongs to a company, being my business model the following:

class Empresa < ActiveRecord::Base
  self.primary_key = 'idempresa'
  has_many :usuarios, class_name: "Empresa", foreing_key: "empresa_id"
end

and the user model:

class Usuario < ActiveRecord::Base

  self.primary_key = 'idusuario'
  belongs_to :empresa, class_name: "Usuario"

end

but at the time of running User.last.company in the rails console, I should get the data of the company of the last user, but what I get is this:

  Usuario Load (1.3ms)  SELECT  "usuarios".* FROM "usuarios"  ORDER BY "usuarios"."idusuario" DESC LIMIT 1
  Usuario Load (0.3ms)  SELECT  "usuarios".* FROM "usuarios" WHERE "usuarios"."idusuario" = $1 LIMIT 1  [["idusuario", 8]]
=> nil

What could I miss? thanks in advance

    
asked by Alexander Marcano 11.07.2016 в 18:35
source

1 answer

1

Try with

class Empresa < ActiveRecord::Base
  self.primary_key = 'idempresa'
  has_many :usuarios
end

class Usuario < ActiveRecord::Base
  self.primary_key = 'idusuario'
  belongs_to :empresa, class_name: "Empresa", foreing_key: "empresa_id"
end
    
answered by 11.07.2016 / 23:50
source