views:

57

answers:

1

I have a parent-child relationship between two objects.

Parent :has_many :children
Child  :belongs_to :parent

When creating a new parent, in the same controller, I'm creating the child.

@mom = Parent.new
@child = Child.new
@mom.children << @child

That all seems to go okay, but this parent has one more attribute - this parent has a favorite child

@mom.favorite_child = @child

Seems like this should work, except let's say that this is the 61st child in the database, so it gets an ID of 61 (and I know this is happening, because when I check the database, the child record has an ID of 61). For some reason, when I assign the @child to the parent's "favorite_child" attribute, "favorite_child" gets set to "1" - when I need it to be set to "61".

Clues?

+2  A: 

Seems like parent needs something like

class Parent
  has_many :children
  has_one :favorite_child, :foreign_key=>'favorite_child_id', :class_name => 'Child'

Otherwise, it doesn't know it's a foreign key relationship, and you're trying to assign an object to an integer.

Tim Hoolihan
Hm, that doesn't seem to work. It leaves my "favorite_child_id" field blank. In the definition above, wouldn't Child need 2 'parent_id' fields, since there are two foreign keys to the same class?
normalocity
Oh, wait, I have my relationships backwards - I have the 'favorite_child_id' field as an attribute of the Parent class - but it should be the other way around somehow, because the foreign key belongs in the class with the 'belongs_to' declaration.
normalocity
i added a foreign key specifier in the code. i don't think you have it backwards
Tim Hoolihan
The Child does get added to the list of children, but the 'favorite_child_id' field is left blank now.I almost think that in the Child class I need something like "belongs_to :parent_that_favors_me, :class_name => 'Parent' as well.I'll keep plugging away, or do away with trying this line of thinking altogether. There must be a cleaner/smarter way to try to define this.
normalocity
What if, instead of trying to define this in terms of a relationship, in the Child class there's a boolean attribute called "is_favored", and then the Parent, when looking for their favorite, could simply iterate through all their children until they find the 'favored' child - hey maybe a Parent even has more than 1 favored child. :PI think that might actually work.
normalocity
that sounds simplest
Tim Hoolihan