Aurel
Aurel

Reputation: 31

ActiveRecord association through multiple tables

I have the following schema for my Rails app :

enter image description here A project has many reviews, each of those reviews is filled out by a unique User to calculate a global score.

We could say that "An Organization of Users handles many Entities that have many Projects which are reviewed by the Users".

As you can see, I have a circular reference since I linked the tables "Users" & "Reviews".

After many tries and many search, I just can't manage to associate a User to a Review...Here is what I did so far:

1. Creation of an association table "UserReviews"

2. Model User

class User < ApplicationRecord
  belongs_to :organization

  ####

  has_many :user_reviews
  has_many :reviews, through: :user_reviews
end

3. Model Review

class Review < ApplicationRecord
  belongs_to :project

  ##

  belongs_to :user_reviews
  has_one :user, through: :user_reviews
end

4. Model UserReview

class UserReview < ApplicationRecord
  belongs_to :user
  belongs_to :review
end

I want to be able to get user.reviews or review.user.

Basically...I have to admit I'm lost despite the documentation. I never had to deal with this kind of issue.

Many thanks for your help!

Upvotes: 1

Views: 711

Answers (1)

shaivik
shaivik

Reputation: 343

Why do you need UserReview model here? I suppose Review model suffices your use case.

Change the Review model to:

class Review < ApplicationRecord
  belongs_to :project
  belongs_to :user
end

Upvotes: 1

Related Questions