Search code examples
ruby-on-railsactiverecordassociations

Active record query using associated model scope


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.


Solution

  • You might need to do something like:

    Food.joins(:requests).merge(Request.where_belongs_to(user))