How to get records where associated's associated_id is a given value

Viewed 53

I have a suburbs activerecord that belongs to a city and have many listings, I want to get the listings where the suburb city is a given value.

    listings = Listing.joins(:suburbs).where('listings.updated_at >= ?', 2.months.ago).where('city_id = ?', city_id)
2 Answers

I am assuming you have these associations defined. Correct me if I am wrong.

In Suburb class:

has_many :listings
belongs_to :city

In Listing class:

belongs_to :suburb

In City class:

has_many :suburbs

Now to fetch all the listings where city is city_id, you need to join listings with suburb and then with city and then you need to filter out the results. Go through this link to understand better

listings = Listing.joins(suburb: :city).where('listings.updated_at >= ?', 2.months.ago).where(cities: {id: city_id })

This should work.

  1. Find a suburb by given id
  2. Find all related listings for the suburb. Check docs for more info.
Suburb.find(city_id).listings.where('updated_at >= ?', 2.months.ago)
Related