João Daniel
João Daniel

Reputation: 8986

What would be that relationship?

I have the following classes:

class MockQuestion < ActiveRecord::Base
    belongs_to :mock
    belongs_to :question
end

class Mock < ActiveRecord::Base
    has_many :mock_questions
    has_many :answers
end

class Question < ActiveRecord::Base
    has_many :mock_questions
    has_many :answers
end

class Answer < ActiveRecord::Base
    belongs_to :question
    belongs_to :mock
end

Since an answer may belong to a Question and a Mock, I would like to connect it to the MockQuestion with same Mock and Question.

I can query it by:

Answers.where(question_id: question_id, mock_id: mock_id)

But I would like to do something as

MockQuestion.answers

Is there any relationship I can use to do that?

P.S.: the answers table has both "mock_id" and "question_id"

Upvotes: 3

Views: 34

Answers (1)

Babar
Babar

Reputation: 1202

Why don't you create self.answers in your MockQuestion class as:

def answers
  Answers.where(mock_id: self.mock.id, question_id self.question.id)
end

And I don't think that kind of relationship is possible. Hence the alternative method

Upvotes: 2

Related Questions