has_many 和 No method 错误问题

2024-03-11

我有两个表:商店和产品。商店模型有一个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)

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

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

这将通过一个查询完成工作,但由于连接的原因,操作结果范围并不那么容易。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

has_many 和 No method 错误问题 的相关文章

随机推荐