ruby 具有多个关联的作用域唯一验证

zengzsys  于 11个月前  发布在  Ruby
关注(0)|答案(1)|浏览(107)

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

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


有什么建议吗?

r1zk6ea1

r1zk6ea11#

您需要为连接表创建一个显式模型,然后在其中验证唯一性

class HotelsUsers < ApplicationRecord

  belongs_to :hotel
  belongs_to :user

  validates_uniqueness_of :user_id, :scope => :hotel_id

end

字符串

相关问题