Mega Man
Mega Man

Reputation: 297

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].

Upvotes: 1

Views: 360

Answers (2)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

Try this:

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

Upvotes: 2

tadman
tadman

Reputation: 211560

If all you care about is the id values you can use pluck:

House.where(...).pluck(:id)

Upvotes: 2

Related Questions