[英]how to query associations with a has_many :through
I have a Rails app with a has_many :through association between User.rb and Practice.rb, with PracticeListing.rb as a join model. 我有一个Rails应用程序,其中User.rb和Practice.rb之间具有has_many:through关联,而PracticeListing.rb作为连接模型。
User.rb User.rb
has_many :practice_listings
has_many :practices, through: :practice_listings
Practice.rb Practice.rb
has_many :practice_listings
has_many :users, through: :practice_listings
PracticeListing.rb PracticeListing.rb
belongs_to :practice
belongs_to :user
In one of the controllers, I call this scope method on user.rb
, passing in the practice_id 在其中一个控制器中,我在user.rb
上调用此scope方法,并传入了user.rb
scope :lawyers_by_practice, lambda {|practice_id|
joins(:practices).
where( users: {practice_id: practice_id},
users: {lawyer: true},)
}
the query from the logs which shows that practice_id is not being used 来自日志的查询,该查询显示没有使用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
Can you explain how I should have written that scope method to get the desired results? 您能解释一下我应该如何编写该作用域方法以获得预期结果吗?
With the current model set up, I could do user.practice_ids
for a certain user and get an array of the practice_ids ['2','4'] 设置好当前模型后,我可以为特定用户执行user.practice_ids
并获得阵列的practice_ids ['2','4']
Update 更新资料
I tried this way (without joining :practices) in the hopes that the query would select only the users with the relevant practice_id, but it returned every user in the db, even those who didn't have a practice 我尝试了这种方式(不加入:practices),希望查询只选择具有相关Practice_id的用户,但是它返回了数据库中的每个用户,即使那些没有练习的用户也是如此。
scope :lawyers_by_practice, lambda {|practice_id|
where( users: {practice_id: practice_id},
users: {lawyer: true},)
}
I also tried this way (by joining :practice_listings instead) but it returned entries for every practice_listing, again ignoring the fact that I only wanted use who had a certain practice id 我也尝试过这种方式(通过加入: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
doesn't have a practice_id
, only PracticeListing
has. 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.