[英]ActiveRecord query on has_many :through in Rails 4
这是我的组织模型:
class Organization < ActiveRecord::Base
has_many :users
has_many :shipments, :through => :users
这是我的发货模型:
class Shipment < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
我正在尝试访问除两个机构以外的所有组织的货件。
此代码有效,但仅返回由我的.where.not
调用返回的FIRST组织的货件。 我想加入我的.where.not
电话返回的所有组织的货物。
Organization.where.not(name: "Admin Org").where.not(name: "Test Organization").first.shipments
谢谢!
我们需要对Shipment
模型进行查询,以获取除这两个组织以外的所有组织的所有货物,我们将使用where.not
caluse进行过滤。
因此查询将如下所示:
@shipments = Shipment.joins(:organization).where.not(organization: {name: "Admin Org"}).where.not(organization: {name: "Test Organization"})
和更清洁:
@shipments = Shipment.joins(:organization).where.not(organization: {name: ["Admin Org", "Test Organization"]})
我最终创建了一个数组,并使用两个.each块将货物转储到其中:
array = []
Organization.where.not(name: ["Admin Org", "Test Organization"]).each { |x| x.shipments.each { |z| array << z } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.