[英]Filter objects with many-to-many table in Rails using has_scope
There are two tables: User and Industry. 有两个表:User和Industry。 User can relate to many industries and a lot of users belong to one Industry. 用户可以涉及多个行业,许多用户属于一个行业。
Industry.rb Industry.rb
class Industry <ApplicationRecord
has_many: users,: through =>: industry_users
has_many: industry_users
end
User.rb User.rb
class User <ApplicationRecord
belongs_to: specialty
has_many: industries,: through =>: industry_users
has_many: industry_users
scope: by_specialty, -> specialty {where (: specialty_id => specialty)}
scope: by_period, -> started_at, ended_at {where ("graduation_date> =? AND graduation_date <=?", started_at, ended_at)}
end
IndustryUser.rb IndustryUser.rb
The relationship between them is many_to_many. 它们之间的关系是many_to_many。 There is a third table IndustryUser which stores two columns. 第三个表IndustryUser存储两个列。
class IndustryUser <ApplicationRecord
belongs_to: user
belongs_to: industry
end
Now I'm developing an API. 现在,我正在开发一个API。 I use has_scope gem to filter users by parameters in get request. 我使用has_scope gem通过get请求中的参数过滤用户。 Above, I successfully filtered them on the specialty and the date of graduation. 上面,我成功过滤了他们的专业和毕业日期。 For example, filtering on the specialty. 例如,对专业进行过滤。
http://localhost:3000/v1/users?by_specialty=1
Filtering by the date of graduation. 按毕业日期过滤。 You should provide period of time. 您应该提供一段时间。
http://localhost:3000/v1/users?
by_period[started_at]=20040101&by_period[ended_at]=20070101
I got stuck when I wanted to get users who belong to a particular industry. 当我想吸引属于特定行业的用户时,我陷入了困境。 Here is an example of a get query 这是获取查询的示例
http://localhost:3000/v1/users?by_industry=2
For example. 例如。 Here, I want it to render all users who are related to the second industry. 在这里,我希望它呈现与第二产业相关的所有用户。 Does anyone know how to filter objects that relate to many-to-many relations using has_scope? 有谁知道如何使用has_scope过滤与多对多关系相关的对象?
I think it's going to be something like: 我认为它将是这样的:
scope: by_industry, -> industry {User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})}
This bit finds the correct industry: 这一点找到了正确的行业:
Industry.where(id: industry)
This bit finds IndustryUser
records that reference the just-found Industry
: 该位查找引用刚刚发现的Industry
IndustryUser
记录:
IndustryUser.where(industry: Industry.where(id: industry))
And then you join on the found industry_users
to find User
s that are reference by the industry_users
. 然后,您加入找到的industry_users
来查找被industry_users
引用的User
。
User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.