amey1908
amey1908

Reputation: 157

.joins with three models

I have three models that needs to be joined together (there are 4 models in play, but I need to join only three of them). The 4 models are user, keyword, question, association.

These are the relationships in the models

  1. A user has many keywords through associations
  2. A keyword has many users through associations
  3. Keyword has many questions
  4. Questions belong to a keyword

The models are -

class User < ActiveRecord::Base
  has_many :associations, dependent: :destroy
  has_many :keywords, :through => :associations 

class Keyword < ActiveRecord::Base      
  has_many :associations, dependent: :destroy
  has_many :users, :through => :associations

  has_many :questions, dependent: :destroy

class Association < ActiveRecord::Base
  belongs_to :keyword
  belongs_to :user

class Question < ActiveRecord::Base
  belongs_to :keyword

Now I need to retrieve all questions for keywords for a particular user (e.g. user_id = 2) using .joins.

Any idea how can I achieve this.

Upvotes: 0

Views: 508

Answers (2)

Dheer
Dheer

Reputation: 793

Please try this:

Question.joins(keyword: [:user]).where(users: {id: 2})

Upvotes: 0

Thaha kp
Thaha kp

Reputation: 3709

You should use

Keyword.joins(:questions, :users).includes(:questions).where(users: {id: 2})

Upvotes: 1

Related Questions