Tony Tony wrote:
Models Associations:
Child
has_many :missing_children
MissingChild
belongs_to :child
Shouldn't the missing-ness of a child be a boolean in the child table?
missing_children_controller.rb
[code]
@children = Child.find(:all, :conditions => ["name LIKE ?",
"%#{params[:search]}%"])
Even if Rails blogs often show run-on lines, you should not follow their example. Breaking things out into separate statements often makes them clearer:
name_match = ['children.name LIKE ?', "%#{params[:search]}%"]
children = Child.find(:all, :conditions => name_match)
Also, don't make children a @data member of the current object until you really need that. And I did not use "" on any string which did not need any "" abilities.
Now children is an array of ids, so extract the ids like this:
ids = children.map(&:id)
And pull the matching missing children:
matching_ids = ['child_id in (?)', ids]
@missing_children = MissingChild.find(:all, :conditions => matching_ids)
I wrote that just to illustrate the in(?) trick. We can simplify it further:
@missing_children = MissingChild.find_all_by_child_id(ids)
Now we will simplify again:
MissingChild.find(:all, :include => :child, :conditions => name_match)
I think I could keep going. And to think that one Joel Spolsky had the nerve to claim ActiveRecord simply didn't understand relational databases! I don't think it was ActiveRecord doing the misunderstanding...