ActiveRecord查询on_many:通过Rails 4

时间:2015-04-10 19:18:34

标签: ruby-on-rails activerecord associations

这是我的组织模型:

  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

谢谢!

2 个答案:

答案 0 :(得分:2)

我们需要对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"]})

答案 1 :(得分:0)

我最终创建了一个数组并使用两个.each块将货件转储到其中:

array = []
Organization.where.not(name: ["Admin Org", "Test Organization"]).each { |x| x.shipments.each { |z| array << z } }