2013-05-10 48 views

回答

5

你可以有一个报表模型多态性与他人

class Report < ActiveRecord::Base 
    belongs_to :reportable, polymorphic: true 
    belongs_to :user 
end 

class Photo < ActiveRecord::Base 
    has_many :reports, as: :reportable 
end 

class Profile < ActiveRecord::Base 
    has_many :reports, as: :reportable 
end 

class User < ActiveRecord::Base 
    has_many :reports     # Allow user to report others 
    has_many :reports, as: :reportable # Allow user to be reported as well 
end 

reports表将像场:

id, title, content, user_id(who reports this), reportable_type, reportable_id 

要确保一个用户只能报一类的一个实例一次(假设用户只能报告一次用户的配置文件),只需在Report模型中添加此验证即可

validates_uniqueness_of :user_id, scope: [:reportable_type, :reportable_id] 

这些设置应该能够满足要求。

进行验证部分,由于Dylan Markow at this answer

+1

你不能有相同名称的关联。用户模型应该是这样的: 'has_many:given_reports,class_name:“Report”' – jokklan 2013-05-10 09:01:01

相关问题