2013-08-21 91 views
1

我有一个模型User,其中has_manyProfile。我也有Report型号,其中belongs_toProfileRails根据另一个表验证属性的唯一性

如何确保一个用户只有一个报告?类似于

class Report 
    validate_uniqueness_of profile_id, scope: :user 
end 

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

+0

您必须使用自定义验证。 Rails不允许在模型范围之外验证唯一性 – techvineet

+0

Hi techvineet:你能建议我该怎么做吗? – AdamNYC

回答

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 
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 
+0

每个配置文件都会有不同的报告。 – AdamNYC