2015-02-11 99 views
0

我有一个的has_many:通过我的应用程序三种模式之间的关系:Rails的has_many_through协会

  • 用户
  • 问题
  • 回答

我使用Active Record Associations docs建立关系。

User.rb

has_many :answers 
has_many :questions, through: :answers 

Question.rb

has_many :answers 
has_many :users, through: :answers 

Answer.rb

belongs_to :question 
belongs_to :user 

这似乎是工作。

User.find(1).questions 
User.find(1).answers 

以上两种方法都正好返回我期望的结果。但是,我需要的是将问答作为一对返回。

我该怎么说:“好吧,获取current_user已经回答的所有问题,并将答案一并返回。”

回答

1

我将它添加到控制器:

@questions = Question.joins(:answers).where(answers: { id: current_user.answers.pluck(:id) }) 

然后在你看来,对于每一个问题,你会得到这样的回答:

- @questions.each do |question| 
    - answers = question.answers.where(user_id: current_user.id) 

你可以(也应该)总是部分代码作为范围移动到模型中。

+0

完美!我在我的视图中使用了以下内容:http://pastebin.com/z9s6mq3m,并按照我的意愿进行显示。谢谢! – brianrhea 2015-02-11 16:12:07