Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda