【问题标题】:ActiveRecord retrieve records in HABTM relationship that belong to array of associated recordsActiveRecord 检索 HABTM 关系中属于关联记录数组的记录
【发布时间】:2016-07-04 19:02:22
【问题描述】:

MaintenanceHABTM MaintenanceOrders

给定一组MaintenanceOrder ids:[1,2,3,4,5],我如何检索与MaintenanceOrders 关联的所有Maintenances

试过这个:

@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

【问题讨论】:

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


    【解决方案1】:

    使用includes,例如:

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

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多