【问题标题】:Filter objects with many-to-many table in Rails using has_scope在 Rails 中使用 has_scope 过滤具有多对多表的对象
【发布时间】: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


    【解决方案1】:

    认为会是这样的:

    scope: by_industry, -> industry {User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})}
    

    这个位找到了正确的行业:

    Industry.where(id: industry)
    

    该位查找引用刚刚找到的IndustryIndustryUser 记录:

    IndustryUser.where(industry: Industry.where(id: industry))
    

    然后您加入找到的industry_users 以查找industry_users 引用的Users。

    User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})
    

    【讨论】:

    • 我把你建议我的范围。有一个错误。
    • "#<:statementinvalid: pg::syntaxerror: error:>
    • 我在rails控制台写了最后一条命令,出现上述错误。
    • IndustryUser中没有主键导致出现错误。我添加了列 id 作为主键。现在它可以工作了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2020-03-23
    • 1970-01-01
    • 2021-07-05
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多