开发者

Finding multiple records through has_one association

开发者 https://www.devze.com 2023-03-19 01:43 出处:网络
My Customer and Person models looks like this: class Customer < ActiveRecord::Base belongs_to :person

My Customer and Person models looks like this:

class Customer < ActiveRecord::Base
  belongs_to :person
  belongs_to :company
end

class Person < ActiveRecord::Base
  has_one :customer
end

How can I get all Person records that have an association with a Custo开发者_如何学Pythonmer?


with sql it might be something like

 Customer.where("customers.person_id IS NOT NULL")

to get Person record you can use join

 Person.joins( :customers ).where("customers.person_id IS NOT NULL")

I'm not sue either where is necessary here (I believe no) so try Person.joins( :customers ) first


person_array = []
Person.all.each do |p|
  unless p.customer.nil?
    person_array << p
  end
end


I don't think it's the fastest query but:

Customer.where('person_id IS NOT NULL').map(&:person)


rails 2.3.x

Customer.all(:include => :person).map(&:person).compact
0

精彩评论

暂无评论...
验证码 换一张
取 消