Given that a User can have_many Addresses, I'm trying to validate that a given user can only have one address for a given address_type
. For example, a user can have a primary address and a billing address, but the user cannot have two primary addresses. How do I enforce that rule on my model, and how to I test it? My current best guess is that I need to validate address_type
's uniqueness scoped to user_id
, but this code is preventing two addresses from existing of the same type. I've seen other people write code very similar to this, but checking on strings instead of on enums.
<!-- language: lang-ruby -->
# user.rb
class User < ApplicationRecord
has_many :addresses
end
# address.rb
class Address < ApplicationRecord
belongs_to :user
enum :address_type => { :primary, :mailing, :billing }
validates :address_type, :uniqueness => { :scope => :user_id }
end