【问题标题】:How to drill through multiple has many/belongs to associations in a where clause?如何在where子句中钻取多个关联/属于关联?
【发布时间】:2013-08-31 12:15:33
【问题描述】:

我有以下 ActiveRecord 模型关联:

一个用户有很多目标;一个目标有许多目标;一个目标有很多任务;一个任务有很多要求。

我正在构建一个 API,我希望 /api/requirements 端点通过钻取上面定义的关联来返回特定用户的所有需求。但是,我在编写 where 子句时遇到了麻烦。这是我目前所拥有的:

Requirement.where('tasks.objectives.goals.user_id = ?', user.id)

但这不起作用。我似乎无法跳过关联来获取 user_id。

【问题讨论】:

    标签: ruby-on-rails activerecord model associations where


    【解决方案1】:

    你可以这样尝试:-

    Requirement.joins(:task => {:objective => :goal}).where('goals.user_id = ?', user.id)

    【讨论】:

    • 谢谢!必须注意joins 使用单数名词,where 使用复数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2014-11-07
    • 2017-04-02
    相关资源
    最近更新 更多