[英]How to set up this belongs_to association in Rails / ActiveRecord?
我有User
和Review
模型。 評論可以有author
和subject
,都指向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.