0
votes

I'm fairly new to rails, and working on an app which essentially allows users to report grievances about other users (just a fun app i want to use with friends). Basically there are just two models, users and reports. A user has many reports and reports belong to a user (ie. a user is associated to reports submitted about them)

Basic model structure:

class User<ApplicationRecord
    has_many :reports  
end

class Report<ApplicationRecord
    belongs_to :user
end

Right now, users can submit new reports and select from a dropdown which user to associate it with, but I would also like to add an association between the report and the user who submitted the report so that I can go through the reports that a user has made and find the user they reported about most. (ie. I want users to have many reports which were written about them and have many reports which they wrote about others)

I don't know how to accomplish this because i need to distinguish this has_many/belongs to relationship from the one I have above. Any ideas?

1

1 Answers

0
votes

I think that you want something like a reporter association, this can be accomplished with an optional reference from the report table to the user table:

So on your report model add the line below:

belongs_to :reporter, class_name: :User, foreign_key: 'reported_by_id', optional: true

Then generate a migration and add the code below:

add_reference :reports, :reported_by, index: true

Then you can do something like:

report.reporter = user1
report.save
or
user2 = report.reporter

Then to get the reports that a particular user made:

Report.where(reported_by_id: user.id)

This may help with the migration, you can simply run rails g migration <name_of_your_migration>, this will generate a file with that name and add the code above inside the change function.

The above example is on rails 5.2, what you are saying with the fix above is exactly: besides the relation, I as report has with the table users, I also have an especial relation with a particular user (you can make that relation optional or not if you have data already in your database I think you should do it optional). I hope this helps! 👍