简体   繁体   English

从外键的外键验证唯一性

[英]Validates uniqueness from foreign key of foreign key

I have 3 models in my rails application, User, Course, and CourseTemplate. 我的Rails应用程序中有3个模型:User,Course和CourseTemplate。

A Course belongs to a User and a CourseTemplate belongs to a Course. 课程属于用户,课程模板属于课程。

What I want to do is to validate the uniqueness between the CourseTemplate name and the User id. 我要做的是验证CourseTemplate名称和用户ID之间的唯一性。

Is this possible? 这可能吗?

Without denormalization of data 无需数据非规范化

class CourseTemplate < ActiveRecord::Base
  belongs_to :course
  has_one :user, through: :course
  validate :unique_course_template_for_user

  private

  def unique_course_template_for_user
    errors.add(:name, 'Must be unique') if CourseTemplate.find_by(user: user.id, name: self.name).count > 0
  end
end

With denormalization of data 随着数据的非规范化

If you're ok with some denormalization of your data, you could add user_id to CourseTemplate, and then simply use the scope feature of validates uniqueness. 如果可以对数据进行一些非规范化,可以将user_id添加到CourseTemplate,然后仅使用验证唯一性的范围功能。

Below I show how to use callbacks to maintain the user_id in the CourseTemplate. 下面,我展示了如何使用回调来维护CourseTemplate中的user_id。 Note that it assumes a course cannot be moved to a different user. 请注意,它假定课程不能移至其他用户。

class CourseTemplate < ActiveRecord::Base
  before_create :copy_user_id_from_course

  validates :name, uniqueness: { scope: :user_id, message: 'Must be unique for the same user'}

  private

  def copy_user_id_from_course
    self.user_id = course.user_id
    true
  end
end

If the course can be moved to a different user, you should add a callback on Course: 如果可以将课程移至其他用户,则应在课程上添加回调:

class Course < ActiveRecord::Base
  after_save :set_course_templates_user, if: :user_id_changed?

  private

  def set_course_templates_user
    course_templates.update_all user_id: self.user_id
  end

end

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

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