Search code examples
ruby-on-railsvalidationvalidates-uniqueness-of

Rails validate uniqueness of attribute according to another table


I have a model User, which has_many Profile. I also have Report model, which 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).


Solution

  • 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