Answer the question
In order to leave comments, you need to log in
Rails polymorphic links and joins?
Hello. Postgresql database How to correctly join a table with a polymorphic field. For example, I need to display a value from a particular table in the organization field, depending on the polymorphic relationship. I am doing at the DB level, are there any other options. Thanks?
class User < ApplicationRecord
belongs_to :userable, polymorphic: true, optional: true
belongs_to :supplier, foreign_key: :userable_id, optional: true
belongs_to :institution, foreign_key: :userable_id, optional: true
end
@users = User
.left_outer_joins( :institution, :supplier )
.select( :username,
" CASE users.userable_type WHEN 'Institution' THEN institutions.name WHEN 'Supplier' then suppliers.name else '' END AS organization"
)
.order( :username )
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question