Reputation: 157
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
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
Reputation: 793
Please try this:
Question.joins(keyword: [:user]).where(users: {id: 2})
Upvotes: 0
Reputation: 3709
You should use
Keyword.joins(:questions, :users).includes(:questions).where(users: {id: 2})
Upvotes: 1