![](/img/trans.png)
[英]Active Record query to find records that match all conditions in Rails has_many through relationship
[英]Query a specific record of a has_many relationship
我已經遇到過幾次這個問題,但是我仍然沒有一個好的解決方案。 我想通過特定關聯的值(“最近”或“收藏夾”)來查找所有用戶...將關聯范圍縮小到1左右的東西。
class User
has_many :group_memberships
has_many :groups, through: :group_memberships do
def favorite
rank(:priority).first
end
end
end
class GroupMembership
belongs_to :group
belongs_to :user
end
class Group
has_many :group_memberships
has_many :users, through: :group_memberships
scope :in_state, ->(state) { where(state: state) }
end
因此,在這種情況下,假設用戶可以對他們所在的組進行排名。我想通過查詢他們最喜歡的組來查找所有用戶。 他們已經設置了所有所屬組的優先級,我們在這里不必擔心。
舉例來說,假設我想查找所有喜歡的組處於特定狀態的用戶。 這是我最近的嘗試,但不起作用...
class User
...
scope :favorite_group_in, lambda { |state|
subquery = Group.rank(:priority).select(:id).limit(1).to_sql
distinct.left_outer_joins(:groups)
.where("groups.id = (#{subquery})")
.merge(Group.in_state(state))
}
end
我試圖創建一個has_one,並嘗試通過它進行查詢,但是那會查詢整個表,而不是將其范圍限定為has_one。 我已經在postgres中嘗試了窗口函數。 我在原始SQL中嘗試過子查詢。 我不能是唯一一個有這個問題的人。 查詢關聯子集的常規解決方案是什么?
起作用的是這個...但是出於性能原因,我正在尋找純SQL實現。
class User
...
scope :favorite_group_in, lambda { |state|
ids = distinct.left_outer_joins(:groups).select { |u| u.groups.primary&.in_state?(state) }.pluck(:id)
where(id: ids)
}
end
我沒有我的Rails環境可以嘗試此操作,但是我相信您可以執行以下操作:
class User < ApplicationRecord
...
scope :favorite_group_in, ->(state) { joins(:groups).where(groups: {state: state}) }
...
在非范圍方面,我們正在執行以下操作:
User.joins(:groups).where(groups: {state: state})
對於您的問題,我不太清楚,但聽起來像是Graph數據庫可以解決的問題。 SQL Server 2017隨附Graph數據庫。 它不是最好的Graph數據庫工具,但至少它是免費的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.