范围内的唯一验证具有许多关联

问题描述 投票:0回答:1

我的酒店有很多用户,用户可能属于很多酒店。我想要进行范围验证,即验证每个酒店的用户用户名和电子邮件的唯一性。目前,我的模型如下所示:

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

有什么建议吗?

ruby-on-rails ruby activerecord associations
1个回答
0
投票

您需要为连接表创建一个显式模型,然后验证那里的唯一性

class HotelsUsers < ApplicationRecord

  belongs_to :hotel
  belongs_to :user

  validates_uniqueness_of :user_id, :scope => :hotel_id


end
© www.soinside.com 2019 - 2024. All rights reserved.