3

I want my users to be able to report other users who have fake profiles, inappropriate photos, use abusive language etc. I was thinking of creating a Report class which would capture this activity. I am just not sure about the associations.

For example, each user can report another user only once. But a lot of users can report a given user. How can I implement this?

pratski
  • 1,448
  • 2
  • 22
  • 37

1 Answers1

9

You can have a Report model with polymorphic association with others

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

Your reports table will have fields like:

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

To make sure an user can only report one instance of one type once(Say an user can only report another user's profile once), just add this validation in Report model

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

These settings should be able to satisfy the requirements.

For validation part, thanks to Dylan Markow at this answer

Community
  • 1
  • 1
Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • 1
    You can't have to association with the same name. The user model should be something like: `has_many :given_reports, class_name: "Report"` – jokklan May 10 '13 at 09:01