1

我有一个模型User,它has_many Profile。我也有Report模型,哪个belongs_to Profile

如何确保一位用户只有一份报告?就像是

class Report
  validate_uniqueness_of profile_id, scope: :user 
end

会很棒,但当然它不起作用。(我不想将用户字段附加到报告,因为它混淆了所有权链)。

4

2 回答 2

1

只是为了让您了解如何实现自定义验证。检查这个

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
于 2013-08-21T13:33:26.050 回答
0

如果我做对了,那么用户的所有个人资料都会有相同的报告,对吗?如果是这样,这意味着配置文件属于用户,那么您为什么不这样建模呢?例如:

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
于 2013-08-21T10:35:08.793 回答