私はUser
とReview
モデルを持っています。これは正常に動作しますRails/ActiveRecordでこのbelongs_to関連付けを設定する方法は?
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
、今、私は反対のレビューを書いた人を表すためにReview
オブジェクトへの2つの別々のUser
のオブジェクトを割り当てることができますレビューはauthor
とsubject
は、両方のUser
を指すことができます。
しかし、ユーザーは、彼が主題または著者のいずれかと関連付けられているレビューの数を「知っている」わけではありません。私はレビューに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
?
まさに私が欲しかったこと、ありがとう –