has_many 和 No method 错误问题 [英] has_many and No method error issue
问题描述
我有两个表:Stores 和 products.商店模型有一个 has_many :products
并且产品有一个 belongs_to :store
I have two tables: Stores and products. The store model has a has_many :products
and the products has a belongs_to :store
我正在尝试在 rails 控制台中执行此操作:
I'm trying to do this though in the rails console:
Store.where(open: true).products.where("created_at <= ?", 1.month.ago)
并得到错误(稍微解释一下):NoMethodError: undefined method products for #<Store
and get the error (paraphrased a bit): NoMethodError: undefined method products for #<Store
推荐答案
不是一件很容易的事情 - products
是在 Store
的实例上定义的方法,并且你在关系上调用它.我可能会去:
Not a very easy thing to do - products
is a method defined on an instance of Store
and you are calling it on the relation. I would probably go with:
Product.where(store_id: Store.where(open:true).pluck(:id)).where("created_at <= ?", 1.month.ago)
这将生成两个 db 调用,但也会返回一个干净且易于查询的范围.另一种方法是使用 join:
which would generate two db calls, but also returns a clean and easy to query scope. Another approach would be to use join:
Product.joins(:store).where(store: { open: true }).where("created_at <= ?", 1.month.ago)
这将完成一个查询的工作,但由于连接,操作结果范围不会那么容易.
This will do the work with one query, but due to the join it won't be that easy to manipulate the resulting scope that easily.
这篇关于has_many 和 No method 错误问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!