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
精彩评论