2017-05-31 80 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