簡體   English   中英

如何在Rails / ActiveRecord中設置這個Emirates_to關聯?

[英]How to set up this belongs_to association in Rails / ActiveRecord?

我有UserReview模型。 評論可以有authorsubject ,都指向User

class Review < ApplicationRecord
  belongs_to :subject, class_name: 'User', optional: true
  belongs_to :author, class_name: 'User', optional: true
end   
class CreateReviews < ActiveRecord::Migration[5.0]
  def change
    create_table :reviews do |t|
      t.references :subject
      t.references :author
    end
  end
end

這可以正常工作,現在我可以將兩個單獨的User對象分配給Review對象,以代表誰針對誰撰寫了評論。

但是,用戶不會“知道”他作為主題或作者與多少條評論相關聯。 我添加了has_and_belongs_to_many :users評論中的has_and_belongs_to_many :users ,反之亦然,盡管可行,但並不是我想要的。

我如何設置關聯才能執行以下操作:

review.author = some_other_user
review.subject = user2
another_review.author = some_other_user
another_review.subject = user2

user2.a_subject_in.count
#=> 2
user2.a_subject_in
#=> [#<Review>, #<Review>]
some_other_user.an_author_in.count
#=> 2

換句話說,我如何查看User被保存為具有belongs_to模型的作者或主題的次數?

如果要在用戶端使用has_many關聯,則需要定義兩個單獨的has_many關系,例如

class User < ApplicationRecord
  has_many :reviews, foreign_key: :author_id
  has_many :subject_reviews, class_name: 'Review', foreign_key: :subject_id
end

現在,您可以簡單地使用

irb(main):033:0> s.reviews
  Review Load (0.2ms)  SELECT "reviews".* FROM "reviews" WHERE "reviews"."author_id" = ?  [["author_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Review id: 1, comment: "random", subject_id: 2, author_id: 1, created_at: "2016-07-12 01:16:23", updated_at: "2016-07-12 01:16:23">]>
irb(main):034:0> s.subject_reviews
  Review Load (0.2ms)  SELECT "reviews".* FROM "reviews" WHERE "reviews"."subject_id" = ?  [["subject_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>

評論: subject_reviews不是一個好名字:),將其更改為您的要求。

我認為您正在尋找以下查詢:

class User
  def referenced_in
    # this fetches you all the reviews that a user was referenced
    Review.where("reviews.author_id = :user_id OR reviews.subject_id = :user_id", user_id: id).distinct
  end
end

User.first.referenced_in #should give you all records a user was referenced

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM