has_many和No方法错误问题

我有两张桌子:商店和产品。 商店模型有一个has_many :products ,产品有一个belongs_to :store

我试图在rails控制台中这样做:

 Store.where(open: true).products.where("created_at <= ?", 1.month.ago) 

并得到错误(稍微解释): NoMethodError: undefined method products for #<Store

这不是一件容易的事情 – products是在Store实例上定义的方法,您在关系上调用它。 我可能会选择:

 Product.where(store_id: Store.where(open:true).pluck(:id)).where("created_at <= ?", 1.month.ago) 

这将生成两个db调用,但也返回一个干净且易于查询的范围。 另一种方法是使用join:

 Product.joins(:store).where(store: { open: true }).where("created_at <= ?", 1.month.ago) 

这将使用一个查询来完成工作,但由于连接,轻松操作生成的范围并不容易。

你倒退了。 由于您可以拥有多个商店,因此Rails不会返回open: true所有产品。

您需要加入并查找商店开放的产品。

 Product.joins(:store).where(store: {open: true}).where("created_at <= ?", 1.month.ago)