1

model Food has many Requests

class Food < ActiveRecord::Base
  has_many :requests
  # scope :where_has_requests, -> { includes(:requests).where.not(requests: { id: nil }) }
end

Requests may belong to User

class Request < ActiveRecord::Base
  # belongs_to :giver, class_name: 'User'
  # belongs_to :receiver, class_name: 'User'
  scope :where_belongs_to, ->(user) { where(giver_id: user.id ).or(where(receiver_id: user.id)) }
end

How to query Food that has Requests which belongs to given User using Request scope?

Food.joins(:requests).where("requests.giver_id=#{user.id} OR requests.receiver_id=#{user.id}")

I've been thinking about this one:

Food.joins(:requests).where(requests.where_belongs_to(user))

But I'm lost. Any idea?

Notice

I have seen Rails querying an associated models scope before I've post this question, though I cannot understand it quite well and I think the cases are different somehow.

glinda93
  • 7,659
  • 5
  • 40
  • 78
  • Does this answer your question? [Rails querying an associated models scope](https://stackoverflow.com/questions/43209400/rails-querying-an-associated-models-scope) – dbugger Jul 29 '20 at 14:26

1 Answers1

2

You might need to do something like:

Food.joins(:requests).merge(Request.where_belongs_to(user))
Samy Kacimi
  • 1,216
  • 9
  • 23