Alex Gausman
Alex Gausman

Reputation: 175

Adding Column Data to a "has_many through" relationship

My rails app is for organizing Assignments which contain Questions. Certain Assignments share Questions, so instead of duplicating that data I have opted to have a third table called AssignmentQuestions that links Questions to Assignments.

The AssignmentQuestions table also has a column called "number".

As an example: I could have a chemistry assignment and a biology assignment which both contain the question "What do you find most interesting about this subject?". In the chemistry assignment this may be question 6, whereas in the biology assignment it may be question 9. In which case my tables (with the relevant entries) would be as follow:

Assignments (id, name)

Questions (id, content)

AssignmentQuestions (assignment_id, questions_id, number)

This setup allows me to associate Assignments with Questions through AssignmentQuestions, as follows:

class Assignment < ApplicationRecord
  has_many :question_associations, class_name: "AssignmentQuestion"
  has_many :questions, through: :question_associations
end

Which allows me to access a given assignment's question's content via an expression in the console:

>> Assignment.first.questions.first.content
=> "What do you find most interesting about this subject?"

What I want, in addition to this, though, is the ability to also access a question's number (unique to that assignment) via a similar expression in the console:

>> Assignment.first.questions.first.number
=> 6

Currently this is not possible, though, since the "number" column resides in the AssignmentQuestions table and not the Questions table itself.

I imagine that I could loop through all of associated Questions and AssignmentQuestions and construct my own hash of objects which contain both the "content" attribute and the "number" attribute. However, I was hoping that there might be a better way to do this via the association itself so that the work occurs in the database.

Is there a way for me to join the numbers column with questions association so that I have access to both?

Upvotes: 0

Views: 39

Answers (1)

arieljuod
arieljuod

Reputation: 15838

You may want to get the first question_association from the assignment instead of the first question: Assignment.first.question_associations.first.number.

It makes more sense to iterate over that association if you need the numbers too (like: Assignment.first.question_associations.order(number: :asc).includes(:question).each do |assoc| and you have assoc.number and assoc.question inside the loop ordered by number and preloading the questions)

Upvotes: 1

Related Questions