0
votes

I need to retrieve information from two separate models which are similar but not the same. I am trying to do things like

I have looked into a few methods however they return an array of active objects rather than an ActiveRecord::Relation which is required for many of the features of my app to work.

Is there any way to return an ActiveRecord::Relation object containing a union of both tables?

I have tried things like

@group = Mymodel.find_by_sql("SELECT id FROM Mymodels 
  UNION SELECT id FROM AnotherModels")

and also explored using the Model.where method however cannot return an ActiveRecord::Relation

EDIT:

Just to be clear I need to return ActiveRecord::Relation that is a union or a merge of the two tables

2

2 Answers

0
votes

Have you tried MyFirstModel.joins(:my_second_models)? Check out details joins in the API here.

EDIT: Single Table Inheritance is a better solution to this problem. See comments below.

0
votes

Try something like this:

Model.joins(:other_model).where("attr1" = :attr1,
                               { attr1: "example" }).group(:attr1)

Since you commented about where, I added the where method on the call. You can also group everything using :group in the end.