【问题标题】:Will this type of filtering work in a belongs_to association?这种类型的过滤是否适用于 belongs_to 关联?
【发布时间】:2013-12-13 16:08:29
【问题描述】:

对于招聘应用程序,我有一个用户模型,其中有许多 common_app。

每个用户实际上只有 1 个 common_app,但如果将来他们有更多,我将其设置为 has_many 关联。

在通用应用程序中,我正在考虑拥有以下数据 ->

user_id:integer
current_city:string
grad_year:integer
read_type:string
listen_speak:string
time_in_china:integer
desired_industry:(not sure, will be a multi-select picklist)
location_pref:(not sure, will be a multi-select picklist)

我对此感到困惑的是,该应用程序的一部分功能是根据用户的回答过滤用户。

通过这种类型的关联,我能否根据用户的回答过滤所有用户?即所有 grad_year 是 2005 年的用户?

如果是,我将如何编写命令来做到这一点?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:
    class User < ActiveRecord::Base
      has_many :apps
    end
    
    class App < ActiveRecord::Base
      belongs_to :user
    end
    
    User.includes(:apps).where('apps.grad_year = 2005')
    

    【讨论】:

    • 太棒了!谢谢岑妮。作为一般建议,您认为这是最好的方法吗?还是您会选择不同类型的关联?
    • 我更新了我的帖子,从用户开始可能看起来更自然。模型设计基于您的描述。我需要更多信息,例如需求或用例来决定是否是最好的方法。
    猜你喜欢
    • 2013-03-29
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 2011-04-30
    相关资源
    最近更新 更多