简体   繁体   中英

Fetch records using join with has_many :through relationship

I have a Hotel model and HotelAmenity model and Amenity model which are related by has_many :through like this:

class Hotel < ActiveRecord::Base
    has_many :hotel_amenities, :dependent => :destroy
    has_many :amenities, through: :hotel_amenities
end

class Amenity < ActiveRecord::Base
    has_many :hotel_amenities, :dependent => :destroy
    has_many :hotels, through: :hotel_amenities
end


class HotelAmenity < ActiveRecord::Base
  belongs_to :amenity
  belongs_to :hotel
end

Now I have hotel_id in my action and I want to fetch all the hotels who have amenities [1,2,3] this is the array of amenity_id .

Good Question !! Don't worry you can solve out this problem using join on the Hotel Model as : First of all you will find the hotel by hotel_id

@hotel= Hotel.find_by_id(params[:user_id))

Now you can find the hotels with amenity_array [1,2,3]

 @hotels = @hotels.joins(:hotel_amenities).where(hotel_amenities: { amenity_id: [1,2,3] }) // this can returns a hotel two or more time


@hotels = @hotels.joins(:hotel_amenities).where(hotel_amenities: { amenity_id: [1,2,3] }).uniq // this will return all hotels without redundant records 

Hope this will work for you.

Try this code:

arr= [1,2,3] 
Hotel.joins(:hotel_amenities).select("hotel_amenities.*,hotels.*").where("hotel_amenities.amenity_id= ?",arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM