ActiveRecord检索属于关联记录数组的HABTM关系中的记录

时间:2016-07-04 19:02:22

标签: ruby-on-rails activerecord rails-activerecord has-and-belongs-to-many

Maintenance HABTM MaintenanceOrders

鉴于MaintenanceOrder ID数组:[1,2,3,4,5],如何检索与Maintenances相关联的所有MaintenanceOrders

试过这个:

@paired_things = Maintenance.where(maintenance_order_id: [1,2,3,4,5])

但它正确失败,因为maintenance_order_id不是维护专栏,当然这没有意义,因为它是HABTM关系......

这是架构的连接表:

create_table "maintenance_orders_maintenances", id: false, force: true do |t|
  t.integer "maintenance_order_id"
  t.integer "maintenance_id"
end

1 个答案:

答案 0 :(得分:0)

使用includes,例如:

Maintenance.includes(:maintenance_orders).where(maintenance_orders: {id: [1,2,3,4,5]})