anishasri
anishasri

Reputation: 71

Ruby on Rails -- validating a unique record, not just unique attributes of a record

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.

Upvotes: 0

Views: 84

Answers (1)

mandar.gokhale
mandar.gokhale

Reputation: 1875

You can try following validation rule:

validates_uniqueness_of :student_id, scope: [:lightbulb_id]

Upvotes: 1

Related Questions