简体   繁体   English

Ruby on Rails —验证唯一记录,而不仅仅是记录的唯一属性

[英]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." 这可能是一个非常大的问题,但是我试图只允许属性为“ lightbulb_id”和“ student_id”的表“ Favorites”的唯一记录。 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 ). 但是,我想验证整个记录的唯一性(因此,请结合lightbulb_idstudent_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. 因此,可以复制lightbulb_idstudent_id (一个学生可以“收藏”多个lightbulb_id),因此,相同的student_id可以使用不同的lightbulb_id在“收藏夹”表中多次出现。 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. 谢谢。

您可以尝试遵循以下验证规则:

validates_uniqueness_of :student_id, scope: [:lightbulb_id]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM