【问题标题】:Rails 4 .where nested model searchRails 4 .where 嵌套模型搜索
【发布时间】:2013-07-10 00:11:51
【问题描述】:

嗨,

我有一个用户模型和一个产品模型。 我的模型产品属于_我的模型用户和用户拥有_许多产品。

我的问题是如何搜索与用户属性匹配的 1 个或多个产品?

例如:Product.where(price: 10) for user.where(id: 2)

嵌套模型搜索的解决方案是什么,我有点迷茫。 非常感谢

【问题讨论】:

    标签: ruby-on-rails search model


    【解决方案1】:

    由于产品属于用户(并且用户有_many产品),您可以查询关闭关系:

    user = User.find(2)
    products = user.products.where(price: 10)
    

    【讨论】:

    • 好的,但它只对一个用户有效。如果我说users = User.where(happy: true) products = users.products.where(price: 10) 我得到一个'NoMethodError: undefined method'
    • 好的,我找到了解决方案:users = User.where(happy: true) products = users.map {|u| u.products.where(price: 10)}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多