has_many and No method error issue

后端 未结 2 1716
眼角桃花
眼角桃花 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:04

    You have it backwards. Since you can have many stores, Rails will not return all the products where open: true.

    You need to join and lookup the products where the store is open.

    Product.joins(:store).where(store: {open: true}).where("created_at <= ?", 1.month.ago)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题