Mohit Verma
Mohit Verma

Reputation: 2089

How to fetch results from 2 ActiveRecord models not having any association

I have 2 models in ActiveRecord, say A and B and both have item_id field which is primary key in both the models.

But, there's no association between them (has_many, belongs_to etc)

A: item_id, attr_1, attr_2

B: item_id, attr_3, attr_4

Now, i need to fetch data from both A and B for some clause involving attr_1 ..attr_4

SQL: select A.item_id, attr_1, attr_2, attr_3, attr_4 from A, B where A.item_id=B.item_id and attr_1="foo" and attr_3="bar"

Option I am thinking right now is, both A and B returning the query break-ups (table, clauses, fields etc) to controller and let controller create the query like above. Then execute the query using ActiveRecord::Base.connection.execute(query)

PS: Don't want to get results from 1st model, iterate over it and get results from 2nd model. Will lead to too many db queries. Also, don't want to merge both the tables as they contain un-related data.

Any better suggestion ?

Upvotes: 0

Views: 115

Answers (1)

yannick
yannick

Reputation: 661

Something like a join?

A.joins('JOIN bs ON bs.item_id = as.item_id AND as.attr_1="foo" AND bs.attr_3="bar"').select("as.attr_1, as.attr_2, bs.attr_3, bs.attr_4")

This is untested but something close should work too.

Upvotes: 0

Related Questions