【发布时间】:2017-11-13 18:25:22
【问题描述】:
有两个表:用户和行业。用户可以涉及多个行业,很多用户属于一个行业。
行业.rb
class Industry <ApplicationRecord
has_many: users,: through =>: industry_users
has_many: industry_users
end
用户.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
它们之间的关系是many_to_many。 第三个表 IndustryUser 存储两列。
class IndustryUser <ApplicationRecord
belongs_to: user
belongs_to: industry
end
现在我正在开发一个 API。我使用 has_scope gem 通过获取请求中的参数过滤用户。以上,我成功过滤了他们的专业和毕业日期。 例如,按专业过滤。
http://localhost:3000/v1/users?by_specialty=1
按毕业日期过滤。您应该提供时间段。
http://localhost:3000/v1/users?
by_period[started_at]=20040101&by_period[ended_at]=20070101
当我想获得属于特定行业的用户时,我遇到了困难。 这是一个获取查询的示例
http://localhost:3000/v1/users?by_industry=2
例如。在这里,我希望它呈现所有与第二行业相关的用户。 有谁知道如何使用 has_scope 过滤与多对多关系相关的对象?
【问题讨论】:
标签: ruby-on-rails ruby has-scope