我的 Rails 5 應用程式中有兩個模型 -User并Login具有以下關聯:
class User < ApplicationRecord
belongs_to :login, optional: true
end
class Login < ApplicationRecord
has_one :user
end
我認為這樣的關聯會阻止登錄擁有多個用戶,但事實證明,在Login.last已經有關聯的用戶物件的情況下:
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">
您仍然可以使用相同的登錄名創建新用戶:
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">
但是當您嘗試獲取最后一個登錄用戶時,您將獲得第一個創建的用戶:
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">
如何防止使用已經使用過一次的登錄名創建新用戶?
uj5u.com熱心網友回復:
您可以使用驗證來說明登錄只能由一個用戶使用。這在模型用戶中看起來像這樣:
validates :login_id, uniqueness: true
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424104.html
