简体   繁体   English

如果模型有一个包含 ID 的集合,Rails 会获取 ID 数组

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

相关问题 Rails activerecord找到父给定的子模型id,当父有一个字段是子id的数组时 - Rails activerecord find parent given child model id, when parent has a field which is array of child ids Rails 4:按ID数组对集合进行排序 - Rails 4: sort collection by array of IDs 如何在Rails中获得where id => id集合的逆函数 - How to get the inverse of where ids => collection of ids in Rails Rails 4-使用collection_select获取具有嵌套属性的中间表的ID数组 - Rails 4 - Using collection_select to get an array of ids for an Intermediate Table with Nested Attributes 如何以collection_select rails形式将多个ID作为数组传递? - how to pass multiple ids as an array in form collection_select rails? 从ID数组获取所有Rails记录 - Get all Rails records from an array of IDs Ruby on Rails-检索ID数组并使用该数组查询其他模型 - Ruby on rails - Retrieve array of ids and using that array to query a different model Ruby on Rails:获取模型的属性集合 - Ruby on Rails: get collection of attributes for a model Rails:返回记录,其中存在所有关联模型的ID数组 - Rails: Return Records Where Array of IDs for Associated Model All Exist 按照给定 ID 数组的顺序,按 ID 查找 model 记录 - Find model records by ID in the order the array of IDs were given
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM