Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Concat Two CollectionProxies with two different models

As the title explains, say I have two ActiveRecord::Base models: SatStudentAnswer and ActStudentAnswer.

I have a Student model

has_many :act_student_answers
has_many :sat_student_answers

I would like to create a collection proxy that concats them together so I can query all student answers together.

student.sat_student_answers.concat(student.act_student_answers)

However I get an ActiveRecord::AssociationTypeMismatch: SatStudentAnswer(#70111600189260) expected, got ActStudentAnswer(#70111589566060) error.

Is there a way to create a collection proxy with two different models so I can continue using the Active Record query interface? If not, what would be the best way to solve this problem?

Thank you for the help!

like image 323
Derrick Mar Avatar asked Dec 06 '25 07:12

Derrick Mar


1 Answers

As far as I know, there isn't way to create Rails AR:Relation with different models in it (I digged in this issue when I needed to create newsfeed with different kind of posts). My solution wasn't very beautiful, but was working: I've created additional model with polymorphic has_many. You could query collection of these new defined models and distinguish sat_answers and act_answers by field answer_type.

like image 58
hedgesky Avatar answered Dec 08 '25 22:12

hedgesky