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
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)
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.