Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
Rails creates many objects for has_one relationship

I've got two models in my Rails 5 app - User and Login with below association:

class User < ApplicationRecord
  belongs_to :login, optional: true
end

class Login < ApplicationRecord
  has_one :user
end

I thought such an association would prevent the Login from having more than one User but it turns out that in a case when the Login.last already has associated user object:

2.4.5 :108 > Login.last.user
 => #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">

You can still create a new user with the same Login:

User.create(first_name: 'test2', last_name: 'test2', login_id: 43
 => #<User id: 2, login_id: 43, first_name: "test2", last_name: "test2", created_at: "2022-02-11 12:03:36", updated_at: "2022-02-11 12:03:36">

But when you are trying to fetch last login user you will get the first created user:

Login.last.user
=> #<User id: 1, type: "Registrant", login_id: 43, first_name: "test", last_name: "test", created_at: "2022-02-11 11:22:25", updated_at: "2022-02-11 11:22:25">

How to prevent creating a new user with a login that has already been used once?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use validation to say that a login just can be use by one user. This will look like this in model User:

validates :login_id, uniqueness: true
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda