Validates uniqueness of `has_many` relationship in Ruby on Rails.
Here is the mockup of users & subjects, the relationship is users can create more than one subjects.
But we need not able to create a duplicate record of every individual user as like if a user John Doe creates as a subject
Ruby once for this user not fair to create
Ruby again, but
Ruby as a subject can create another user but only once not a duplicate.
See the below mockup
If you concentrate this image you can’t find the subject name use a duplicate for a user.
Now we can see our models like
#=> user.rb class User < ApplicationRecord has_many :subjects end #=> subject.rb class Subject < ApplicationRecord belongs_to :user end
Now if you create subjects it will take duplicates of a subject, so we add
validates_uniqueness_of :name then it will take only once & not able to create multiple users subject as
Now we can change our
subject model slightly, see the below:
#=> subject.rb class Subject < ApplicationRecord belongs_to :user validates_uniqueness_of :name, scope: :user_id end
we added here
scope: :user_id & that’s why it’s can take name unique based on user, a user can’t create a duplicates of name.