B
B
Bogdan2017-07-17 14:43:38
Ruby on Rails
Bogdan, 2017-07-17 14:43:38

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 question

Ask a Question

731 491 924 answers to any question