zethix
zethix

Reputation: 125

can you force ActiveRecord find to include nil when associated record not found

Is there a way to force :include in ActiveRecord find to output nil in results where conditions are not met?

For example if I have classes: Parent and Children. Parent has many childrens and I do something like this:

children_ids = [1,2,3]
my_parent = Parent.find(:all,
                        :include => :children,
                        :conditions => ['parent.id = 1 AND children.id IN (?)', children_ids])

Assuming that I have only childrens with id 2 and 3 statement:

my_parent.children

will return array with two childrens. But I would like to know which one they are (second and third in my children_ids array). So is it possible for :include to input nil for child that I'm missing?

If this description is too confiusing then let me know and I will try to present it better.

Upvotes: 0

Views: 130

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

If you want to find out what records were missing, you can do it in rubyland by processing retrieved records.

retrieved_ids = my_parent.children.map(&:id)
unretrieved_ids = children_ids - retrieved_ids

Upvotes: 1

Related Questions