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
  • 19,887
  • 29
  • 98
  • 154

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
  • 12,848
  • 2
  • 31
  • 53
techvineet
  • 5,041
  • 2
  • 30
  • 28
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,669
  • 14
  • 21