1

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

AdamNYC
  • 17,771
  • 28
  • 90
  • 147

2 Answers2

1

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
Matt
  • 7,915
  • 2
  • 18
  • 33
techvineet
  • 4,691
  • 2
  • 25
  • 27
0

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
iwiznia
  • 1,649
  • 14
  • 21