简体   繁体   English

Rails根据另一个表验证属性的唯一性

[英]Rails validate uniqueness of attribute according to another table

I have a model User , which has_many Profile . 我有一个模型User ,它具有has_many Profile I also have Report model, which belongs_to Profile . 我也有Report模型, belongs_to Profile

How can I make sure that one user has only one report? 如何确定一位用户只有一份报告? Something like 就像是

class Report
  validate_uniqueness_of profile_id, scope: :user 
end

would be great, but of course it doesn't work. 会很棒,但是当然不起作用。 (I don't want to attach user field to Report, because it mixes up ownership chain). (我不想将用户字段附加到报表,因为它混合了所有权链)。

Just to give you an idea on how to implement custom validations. 只是为了让您了解如何实现自定义验证。 Check this 检查一下

class Report
    validate :unique_user

    def unique_user
        if self.exists?("profile_id = #{self.profile_id}")
          errors.add(:profile_id, "Duplicate user report")
        end
    end
end

If I get it right, then all the profiles of a user will have the same report, right? 如果我理解正确,那么用户的所有个人资料都将具有相同的报告,对吗? If that's so, it means that a profile belongs to a user, so why don't you model it like that? 如果是这样,则意味着配置文件属于用户,那么为什么不那样建模呢? Eg: 例如:

class User 
  has_many :profiles
  has_one :report
end

class Profile
  belongs_to :user
  has_one :report, through: :user
end

class Report
  belongs_to :user
end

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

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