2

I have these three models:

User:

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

Store:

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

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

Permission:

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

How can i validate the uniqueness of the user.email based on the store.id?

Mattia M.
  • 464
  • 1
  • 4
  • 16

1 Answers1

2

You don't.

You should validate the uniqueness of the users email in User. And validate the uniqueness of the user_id and store_id in Permission.

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

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

This allows a user to have permissions for multiple stores - but does not allow duplicates. In general when linking records together use id's - not something like emails.

max
  • 96,212
  • 14
  • 104
  • 165
  • As @wesley6j allready stated - it makes no sense that users should be able to create multiple accounts with the same email - you allready have a many to many assocation that will allow a single user account to be linked to any number of stores. – max May 31 '17 at 11:43