Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate uniqueness of value between multiple fields

I understand that validating uniqueness of a standard, single field like "username" is easy. However, for something that has an unlimited number of inputs like, for example, "Favorite Movies" where a user can add as many favorite movies, is something I can't figure out.

They can choose to add or remove fields via the builder, but how do I ensure that no two or more entries are duplicates?

like image 919
stewart715 Avatar asked Dec 07 '25 10:12

stewart715


1 Answers

I think the easiest way to accomplish something like this is to validate the uniqueness of something in a scope. I can't say for sure how it would fit in your scenario since you did not describe you model associations but here is an example of how it could work in a FavoriteMovie model:

class FavoriteMovie < ActiveRecord::Base
  belongs_to :user

  validates_uniqueness_of :movie_name, :scope => :user_id
end

This makes sure that there can't be two movie names that are the same for one specific user.

like image 110
DanneManne Avatar answered Dec 10 '25 00:12

DanneManne