2017-05-31 59 views
2

我有这三种模式:轨道4 - 验证独特性的has_many通过

用户:

class User < ActiveRecord::Base 
    validates :name, presence: true 
    validates :surname, presence: true 
    validates :email, presence: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } 

    has_many :permissions, dependent: :destroy 
    has_many :stores, through: :permissions 
end 

商店:

class Store < ActiveRecord::Base 
    validates :name, presence: true 
    validates :description, presence: true 

    has_many :permissions 
    has_many :users, through: :permissions 
end 

权限:

class Permission < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :store 
end 

哪有我验证了01的独特性基础上,store.id

+0

你不验证电子邮件的独特性在用户模式?不应该将电子邮件作为用户的唯一标识符吗? – wesley6j

+0

我需要允许用户使用同一封电子邮件订阅多个商店。 – user4523968

+1

更有意义的是,用户可以订阅多个商店而无需注册多个账户? – wesley6j

回答

2

你不知道。

您应该验证的用户的电子邮件的唯一性User。并验证了user_idstore_id的独特性在Permission

class User < ApplicationRecord 
    # ... 
    validates_uniqueness_of :email 
end 

class Permission < ApplicationRecord 
    validates_uniqueness_of :user_id, scope: 'store_id' 
end 

这允许用户拥有多个商店的权限 - 但不允许重复。一般来说,将记录链接在一起时使用的是ID--而不是电子邮件。

+0

正如@ wesley6j媒体链接声明 - 它没有任何意义,用户应该能够创建具有相同的电子邮件多个帐户 - 你媒体链接有一个多对多的ASSOCATION,将允许单个用户帐户链接到任何数量的店面。 – max