2014-04-25 54 views
3

我有以下类别:那会是什么样的关系?

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 

因为答案可能属于一个问题和模拟,我想将它连接到与相同的模拟和问题的MockQuestion。

我可以查询它:

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

但我想做些事情的

MockQuestion.answers 

有没有我可以用来做什么关系?

PS:答案表有两个“mock_id”和“question_id”

回答

2

你为什么不你MockQuestion类作为创建self.answers

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

而且我不认为这种的关系是可能的。因此,替代方法

+0

是的,这就是我正在使用的。但由于这不是一种关系,我不能急于加载它。 –

+1

在这种情况下,您可以使用rails join命令进行加载,这里是一个很好的链接http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes .html,这会让你开始。 – Babar

相关问题