# How to use ActiveRecord associations to select from related

**URL:** <https://www.ruby-forum.com/t/how-to-use-activerecord-associations-to-select-from-related/149995>\
**Category:** Rails\
**Created:** [October 2, 2008, 2:22am UTC](https://www.ruby-forum.com/t/how-to-use-activerecord-associations-to-select-from-related/149995 "2008-10-02T02:22:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rup](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/71c47a/32.png) [@rup](https://www.ruby-forum.com/u/rup)\
**Post date:** [October 2, 2008, 2:22am UTC](https://www.ruby-forum.com/t/how-to-use-activerecord-associations-to-select-from-related/149995/1 "2008-10-02T02:22:55Z")

</div>

table “users” [Stores user information]  
id, username, password,email

table “exams” [Stores exam information]  
id, name, description

table “questions” [stores question information]  
id, question, opt1, opt2, opt3,opt4, correct

table “exam\_questions” [stores selection of questions for a particular  
exam or test]  
id, exam\_id, question\_id

table “user\_answers” [stores the user response to the questions in exam]  
id, user\_id,exam\_id,question\_id,userans, created\_at

Associations in my models:

“user.rb”  
has\_many :user\_answers

“exam.rb”  
has\_many :exam\_questions  
has\_many :questions, :through=\>:exam\_questions  
has\_many :user\_answers

“question.rb”  
has\_many :exam\_questions  
has\_many :exams, :through=\>:exam\_questions  
has\_many :user\_answers

“exam\_question.rb”  
belongs\_to :exam  
belongs\_to :question

“user\_answer.rb”  
belongs\_to :user  
belongs\_to :question  
belongs\_to :exam

Now what I need is:

1. To extract the exam and question details by running a query in  
ExamQuestion table. Is this possible?  
something like: @detail=ExamQuestion.find(:all) and then looping also  
displaying the question and exam detail. I don’t want to use find\_by\_sql

2. Also to extract form UserAnswer table and display the exam detail,  
question detail and user answer with a single hit in database.

In general terms, I want to use the features of Active Record  
associations to run a query to extract as much informaton as possible  
from multiple tables.  
This is to avoid multiple queries.  
Please help.

---

<div class="post-metadata">

**Author:** ![rup](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/71c47a/32.png) [@rup](https://www.ruby-forum.com/u/rup)\
**Post date:** [October 2, 2008, 4:47pm UTC](https://www.ruby-forum.com/t/how-to-use-activerecord-associations-to-select-from-related/149995/2 "2008-10-02T16:47:38Z")

</div>

Please help me by responding to the above post.

Your help will be appreciated.

Thanks
