Mega Man Mega Man - 1 month ago 8
Ruby Question

Rails get array of IDs if model has a collection with an ID in it

High level what I'm trying to do.
I have a

House
model and a
House
has_many
Rooms
. Both House and Room have an id property. I'm trying to get an array of House ids that contain a rooms with a certain id:
data: (rails 4.2.6)

houses = [{
id: 1,
rooms: [{ id: 1}, {id: 2}, {id: 3}]
},{
id: 2,
rooms: [{id: 2}]
}]


pseudocode

House.where(rooms: contain(id: 2))


this should return [1,2] because both houses have room id of 2

House.where(rooms: contain(id: 1))


this should return [1].

Answer

Try this:

House.joins(:rooms).where(:rooms => {:id => 5}).pluck(:id)