Mega Man Mega Man - 11 months ago 53
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

model and a
. 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}]


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 Source

Try this:

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