zcserei
zcserei

Reputation: 665

Query a list of records with ActiveRecord where foreign keys of each item are present in a hash

I have four models - User, Agency, Listing and Inquiry.

A User has_one Agency, an Agency has_many Listings, and a Listing has_many Inquiries.

I have a query where I get a :user_id, so I can get its Agency and the collection of Listings.

I need the Inquiries that belong to a certain Listing.

My approach is the following, obviously I'm looking for a replacement for all. I'd like to make a query where I can list all the inquiries where :listing_id is the id of one of the listings in @listings.

  def index
    @agency = User.find(params[:user_id]).agency
    @listings = @agency.listings

    @inquiries = Inquiry
      .all

    render json: @inquiries
  end

I tried combining various select, includes, where, etc. methods but couldn't come up with a working solution.

Thank you for your help, much appreciated!

Upvotes: 1

Views: 948

Answers (2)

Dyaniyal Wilson
Dyaniyal Wilson

Reputation: 1060

We can use mutiple joins in a single query to reach till the resulted association.

def index
  @inquiries = Inquiry.joins(listing: { agency: :user }).where(users: { id: params[:user_id] })

 render json: @inquiries
end

Upvotes: 3

Beartech
Beartech

Reputation: 6411

First off, if you are using something like RuboCop it will probably warn you that you usually only pass one, possibly two instance variables in a method like this. Not that I haven't done it, it's just not considers optimal Rails. That said:

One way might be this:

def index
  @agency = User.find(params[:user_id]).agency
  @listings = @agency.listings

  @inquiries = Inquiry.where(listing_id: @listings.pluck(:id))

 render json: @inquiries
end

You can pass an array of things to match with where. pluck gives you an array of what ever columns you pass to it.

Upvotes: 0

Related Questions