Home > other >  Rails creates many objects for has_one relationship
Rails creates many objects for has_one relationship

Time:02-15

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?

CodePudding user response:

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
  • Related