0

I have 3 separate tables A, B and C. Table A and table B are two separate tables that have very similar attrs, in fact table B is just an extension of table A but it had to be separated due to business requirements. Both tables has_many relation to table C. Below is a better representation of the relationship between the three table

class A < ActiveRecord::Base
  has_many :c, dependent: :destroy
end

class B < ActiveRecord::Base
  has_many :c, dependent: :destroy
end

class C < ActiveRecord::Base
  belongs_to :a, optional: true
  belongs to :b, optional:true
end

So the problem comes when I'm trying querying information from table C and need the information from table A and B as well. If I do C.where(user_id: 5).joins(:a), it only returns me the record that can join with A. Likewise for table B. But if I do C.where(user_id: 5).joins(:a, :b) I get a [] response. FWIW, the information I need from A and B are have the same column names when accessing them. Still very new to rails, any help is appreciated.

Ryan Tin
  • 381
  • 4
  • 12
  • `.joins` creates a LEFT INNER join which will only include rows with a match in the joined table. `.left_joins` creates a OUTER JOIN which will include rows even without a match. Neither will actually include any columns from the joined table in the result unless you actually manually select them. https://stackoverflow.com/questions/38549/what-is-the-difference-between-inner-join-and-outer-join – max May 24 '21 at 13:39
  • Neither will actually solve a N+1 query issue - in that case you want `.includes` which will load the association in a single query. It does an outer join. – max May 24 '21 at 14:28
  • @max thanks for the suggestion. It looks like `.includes` might be good. I read your message earlier which mentioned polymorphic association which seems like it could be the better way to solve this in the long run. Would that be a better solution? – Ryan Tin May 24 '21 at 14:49
  • Yes and no. Polymorphic assocations will give you a single assocation. But you can't use foreign key constraints - its also a bit of hack that really just hides the problems related to the object–relational impedance mismatch. For example even when you join a polymorphic association you still have to use the correct table names in `.where`. – max May 24 '21 at 15:07

0 Answers0