[英]how to query associations with a has_many :through
我有一個Rails應用程序,其中User.rb和Practice.rb之間具有has_many:through關聯,而PracticeListing.rb作為連接模型。
User.rb
has_many :practice_listings
has_many :practices, through: :practice_listings
Practice.rb
has_many :practice_listings
has_many :users, through: :practice_listings
PracticeListing.rb
belongs_to :practice
belongs_to :user
在其中一個控制器中,我在user.rb
上調用此scope方法,並傳入了user.rb
scope :lawyers_by_practice, lambda {|practice_id|
joins(:practices).
where( users: {practice_id: practice_id},
users: {lawyer: true},)
}
來自日志的查詢,該查詢顯示沒有使用Practice_id
User Load (1.1ms) SELECT "users".* FROM "users" INNER JOIN "practice_listings" ON "practice_listings"."user_id" = "users"."id" INNER JOIN "practices" ON "practices"."id" = "practice_listings"."practice_id" WHERE "users"."lawyer" = 't' AND (reputation IS NOT NULL) ORDER BY reputation DESC
您能解釋一下我應該如何編寫該作用域方法以獲得預期結果嗎?
設置好當前模型后,我可以為特定用戶執行user.practice_ids
並獲得陣列的practice_ids ['2','4']
更新資料
我嘗試了這種方式(不加入:practices),希望查詢只選擇具有相關Practice_id的用戶,但是它返回了數據庫中的每個用戶,即使那些沒有練習的用戶也是如此。
scope :lawyers_by_practice, lambda {|practice_id|
where( users: {practice_id: practice_id},
users: {lawyer: true},)
}
我也嘗試過這種方式(通過加入:practice_listings來代替),但是它為每個Practice_listing返回條目,再次忽略了我只想使用具有特定練習ID的事實
scope :lawyers_by_practice, lambda {|practice_id|
joins(:practice_listings).
where( users: {practice_id: practice_id},
users: {lawyer: true},)
}
User
不具有practice_id
,只有PracticeListing
了。
scope :lawyers_by_practice, lambda {|practice_id|
joins(:practices,:practice_listings).
where( practice_listings: {practice_id: practice_id},
users: {lawyer: true},)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.