代码之家  ›  专栏  ›  技术社区  ›  MSC

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

  •  0
  • MSC  · 技术社区  · 6 年前

    在线程化讨论上下文中,我希望允许用户报告攻击性评论。我有一个报告表,我想在其中记录写评论的用户和投诉的用户。

    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 回复  |  直到 6 年前
        1
  •  2
  •   Anand    6 年前
    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