Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!