我的酒店有很多用户,用户可能属于很多酒店。我想要进行范围验证,即验证每个酒店的用户用户名和电子邮件的唯一性。目前,我的模型如下所示:
class User < ApplicationRecord
has_many :hotel_users
has_many :hotels, through: :hotel_users
end
还有我的酒店型号:
class Hotel < ApplicationRecord
has_many :hotel_users
has_many :users, through: :hotel_users
end
有什么建议吗?
您需要为连接表创建一个显式模型,然后验证那里的唯一性
class HotelsUsers < ApplicationRecord
belongs_to :hotel
belongs_to :user
validates_uniqueness_of :user_id, :scope => :hotel_id
end