开发者

Why is my new ID always "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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜