has_many and No method error issue

后端 未结 2 1725
眼角桃花
眼角桃花 2021-01-17 04:17

I have two tables: Stores and products. The store model has a has_many :products and the products has a belongs_to :store

I\'m trying to do

2条回答
  •  星月不相逢
    2021-01-17 05:13

    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)
    

    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.

提交回复
热议问题