Rails validate uniqueness of attribute according to another table

1.5k views Asked by At

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).

2

There are 2 answers

0
techvineet On BEST ANSWER

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
0
iwiznia On

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