[英]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
.我有一个House
模型和一个House
has_many Rooms
。 Both House and Room have an id property. House 和 Room 都有一个 id 属性。 I'm trying to get an array of House ids that contain a rooms with a certain id: data: (rails 4.2.6)我正在尝试获取包含具有特定 id 的房间的 House 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这应该返回 [1,2] 因为两所房子的房间 id 都是 2
House.where(rooms: contain(id: 1))
this should return [1].这应该返回 [1]。
如果您只关心id
值,您可以使用pluck
:
House.where(...).pluck(:id)
尝试这个:
House.joins(:rooms).where(:rooms => {:id => 5}).pluck(:id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.