0

This might be a very question, but I'm trying to allow only unique records for a table called "Favorites" with attributes "lightbulb_id" and "student_id." I know about model validations

class Person < ActiveRecord::Base
  validates_uniqueness_of :user_name
end

But, I want to validate the uniqueness of the entire record (so the combination of lightbulb_id and student_id). So, lightbulb_id and student_id can be duplicated (a student can "favorite" multiple lightbulb_id's) and consequently the same student_id can appear multiple times in the Favorites table with different lightbulb_ids. But the specific combination shouldn't be duplicated (a student cannot favorite a lightbulb twice)

This might be a very basic question, any suggestions would be appreciated. Thanks.

Baldrick
  • 23,882
  • 6
  • 74
  • 79
anishasri
  • 71
  • 1
  • 5

1 Answers1

1

You can try following validation rule:

validates_uniqueness_of :student_id, scope: [:lightbulb_id]
mandar.gokhale
  • 1,876
  • 1
  • 18
  • 37
  • 1
    validates :lightbulb_id, uniqueness: { scope: :student_id } I tried this and added a unique index on my Favorites table and it seems to be working. I'm not entirely sure how the scope specification works though. Does it check for uniqueness of the student_id and attribute specified in scope combined? – anishasri Dec 23 '15 at 16:39