2016-07-12 20 views
0

私はUserReviewモデルを持っています。これは正常に動作します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のオブジェクトを割り当てることができますレビューはauthorsubjectは、両方の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

答えて

4

あなたはユーザー側でhas_many関連付けを使用する場合は、あなたが今と

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

のような二つの別々のhas_manyの関係を定義する必要がありますこれを簡単に使用できます

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はいい名前ではありません:)あなたの要件に変更してください。

+0

まさに私が欲しかったこと、ありがとう –

0

私はこのクエリを探していると思う:

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 
関連する問題