Rails 5.2-如何将报表模型与两个用户关联

时间:2018-12-08 07:05:15

标签: ruby-on-rails activerecord

在主题讨论的上下文中,我希望允许用户报告令人反感的评论。我有一个“报告”表,我要在其中记录撰写评论的用户和提出投诉的用户。

“我的报告”表当前如下:

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记录投诉用户的ID。 author_id记录评论作者的ID。

关联设置如下:

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

在控制台中,我可以查询如下:

r = Report.last
=> #<Report id: ...
r.user
=> #<User id: ...

但我无法查询

r.author
=> NoMethodError: undefined method `author' for #<Report:0x000000082ef588>

第一个问题是如何启用这种查询。

第二,我希望能够查询针对特定用户的投诉(报告),所以:

u = User.last
=> #<User id: ...
u.complaints
=> #<ActiveRecord::AssociationRelation [...

我还需要添加什么来启用这些查询?

1 个答案:

答案 0 :(得分:2)

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