Home > front end >  Rails Query - Join on non-primary column
Rails Query - Join on non-primary column

Time:11-23

I have three models: Foo, Bar and Profile. The first two models reference Profile.

I would like join Foo and Bar without having to join Profile e.g.

class Foo < ApplicationRecord
  belongs_to :profile
end

class Foo < ApplicationRecord
  belongs_to :profile
end

class Profile < ApplicationRecord
end

The SQL would look something like:

SELECT *
FROM foo 
INNER JOIN bar ON foo.profile_id = bar.profile_id

I could do the following, but I don't want to join Profile as it's a much larger table.

Foo.joins(profile: :bar)

CodePudding user response:

You can achieve this by using raw SQL query in joins.

# assuming you have foos and bars tables

Foo.joins("LEFT JOIN bars ON foos.profile_id = bars.profile_id")

Hope it works for you!

CodePudding user response:

class Foo < ApplicationRecord
  def self.join_bars
    bars = Bar.arel_table
    j = arel_table.join(bars)
                  .on(arel_table[:profile_id].eq(bars[:profile_id]))
    joins(j.join_sources)
  end
end
  • Related