Reputation: 3386
In a threaded discussion context, I want to allow Users to report offensive Comments. I have a Reports table in which I want to record both the User who wrote the Comment and the User who made the complaint.
My Reports table is currently as follows:
create_table "reports", force: :cascade do |t|
t.bigint "comment_id"
t.bigint "user_id"
t.integer "author_id"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["comment_id"], name: "index_reports_on_comment_id"
t.index ["user_id"], name: "index_reports_on_user_id"
end
user_id
records the id the user making the complaint. author_id
records the id of the author of the comment.
The associations are set up as follows:
report.rb
class Report < ApplicationRecord
belongs_to :comment
belongs_to :user
belongs_to :author, class_name: 'User', foreign_key: 'author_id'
end
user.rb
class User < ApplicationRecord
# Nothing yet, but presumably need something
end
In the console, I can query as follows:
r = Report.last
=> #<Report id: ...
r.user
=> #<User id: ...
but I can't query
r.author
=> NoMethodError: undefined method `author' for #<Report:0x000000082ef588>
So the first question is how can I enable this type of query.
Secondly, I'd like to be able to query the complaints (Reports) made against particular Users, so:
u = User.last
=> #<User id: ...
u.complaints
=> #<ActiveRecord::AssociationRelation [...
What do I need to add to enable these queries too?
Upvotes: 0
Views: 151
Reputation: 6531
class Report < ApplicationRecord
belongs_to :comment
belongs_to :user
belongs_to :author, class_name: 'User', foreign_key: 'author_id'
end
class User < ApplicationRecord
# Nothing yet, but presumably need something
has_many :reports #user reports
#Query the complaints (Reports) made against particular Users
has_many :complaints, class_name: 'Report', foreign_key: 'author_id'
end
Upvotes: 2