Reputation: 20538
I am creating an Rail 5 app and in this app I got several models. Survey, Question and SurveyQuestion (join table).
Survey
has_many :survey_questions, dependent: :destroy
has_many :questions, :through => :survey_questions
Question
has_many :question_surveys
has_many :surveys, :through => :question_surveys
SurveyQuestion
belongs_to :survey
belongs_to :question
The SurveyQuestion object got an attribute called sorting. I want to be able to access this attribute when getting the question objects but I only get the questions objects back (which is good) but I need this attribute from the join table too (sorting):
@survey.questions
How can I access the join table attribute? Alternatively I want to sort the @survey.questions by the join table attribute (sorting).
Do I have to fetch question join table objects and then build a new array of questions in Survey method?
def ordered_question
questions = []
items = self.survey_questions.joins(:question).order("sorting desc")
items.each do |item|
questions << item.question
end
questions
end
Upvotes: 0
Views: 93
Reputation: 11193
Why not sort the collection array?
@survey.survey_questions.sort_by{ |sq| -sq.sort }.map{ |sq| sq.question }
Check if you have e typo: has_many :question_surveys
Upvotes: 1