我有三個模型:Foo,Bar和Profile。前兩個模型參考Profile。
我想加入 Foo 和 Bar 而不必加入 Profile eg
class Foo < ApplicationRecord
belongs_to :profile
end
class Bar < ApplicationRecord
belongs_to :profile
end
class Profile < ApplicationRecord
end
SQL 看起來像:
SELECT *
FROM foo
INNER JOIN bar ON foo.profile_id = bar.profile_id
我可以執行以下操作,但我不想加入,Profile因為它是一張更大的桌子。
Foo.joins(profile: :bar)
uj5u.com熱心網友回復:
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
你也可以只設定一個關聯:
class Foo < ApplicationRecord
belongs_to :profile
has_many :bars,
primary_key: :profile_id, # the column on this table
foreign_key: :profile_id # the column on the other table
# or for one to one
has_one :bar,
primary_key: :profile_id, # the column on this table
foreign_key: :profile_id # the column on the other table
end
Foo.joins(:bars)
uj5u.com熱心網友回復:
您可以通過在joins.
# assuming you have foos and bars tables
Foo.joins("LEFT JOIN bars ON foos.profile_id = bars.profile_id")
希望這對你有用!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364005.html
標籤:红宝石轨道
