【问题标题】:How to limit results through an association in rails如何通过rails中的关联限制结果
【发布时间】:2019-05-14 09:41:16
【问题描述】:

我有一个属于某个用户的评分模型,我想只获取用户已确认的评分。

Rating.includes(:user).merge(User.where.not(confirmed_at: nil))

【问题讨论】:

    标签: ruby-on-rails ruby model scope


    【解决方案1】:

    Rails 5+ 语法:

    Rating.joins(:user).where.not(user: { confirmed_at: nil })
    

    【讨论】:

    • 为什么要去掉包含?只是为了减少代码?
    • Rails includes 为@Ursus 着想Rating.includes(:user).references(:user).where(User.arel_table[:confirmed_at].not_eq(nil))
    【解决方案2】:

    改成。

    Rating.joins(:user).merge(User.where.not(confirmed_at: nil))
    

    【讨论】:

    • 为什么要去掉包含?只是为了减少代码?
    • 包括急切加载关联,而 joins 用于内部连接。为了使用包含,您必须使用引用(:用户)。您可以在查询中使用 join 或使用 includes(:user) 和 references(:user)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2013-04-18
    • 2023-03-07
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多