0

I have many users, and they has_many :social_media_accounts, however, I want to only allow a unique social_media_account.type per user,

e.g. User "Bob" can only have one social_media_account.type of "Twitter"

How do I do this?

class User < ApplicationRecord
  has_many :social_media_accounts
end

class SocialMediaAccount < ApplicationRecord
  belongs_to :user

  enum type: [
    twitter:   1,
    facebook: 2,
    linkedin: 3
  ]
end
Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79

1 Answers1

1

You can solve it two ways:

  1. On DB side: create migration for unique index for your user_id and social_media_account_id. Example is here: A migration to add unique constraint to a combination of columns

  2. On the app side: create validation preventing of creating more than one social_media_account for one user (Example: validates :name, uniqueness: { scope: :year}). More info here: http://guides.rubyonrails.org/active_record_validations.html

Community
  • 1
  • 1
Andrey Saleba
  • 2,167
  • 4
  • 20
  • 27