Ruby on rails Can';t访问儿童&x27;她的父母有一个

Ruby on rails Can';t访问儿童&x27;她的父母有一个,ruby-on-rails,nested,has-one,Ruby On Rails,Nested,Has One,我这里有一个令人困惑的问题。我有两个模型,有一对一的关系。我有一个表单,它使用字段_创建子实例。但是,当我尝试从子模型访问父模型时,它只得到一个nil 我试图提供一个简明而简单的例子来说明以下问题: class Parent has_one :child accepts_nested_attributes_for :child attr_accessible :child_attributes end class Child belongs_to :parent valid

我这里有一个令人困惑的问题。我有两个模型,有一对一的关系。我有一个表单,它使用字段_创建子实例。但是,当我尝试从子模型访问父模型时,它只得到一个nil

我试图提供一个简明而简单的例子来说明以下问题:

class Parent
  has_one :child
  accepts_nested_attributes_for :child
  attr_accessible :child_attributes
end

class Child
  belongs_to :parent
  validate :parent_is_called_mum

  def parent_is_called_mum
    parent.name.equals?("mum")
  end
end
问题是
parent.name.equals?(“mum”)
返回一个错误:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.name

为什么关系返回为nil?

我不确定,但请尝试使用
self.parent.name.equals?(“mum”)

self可能是隐式的,所以这可能不是您的解决方案


编辑:在数据库中,是否确定
childs
表中的
parent\u id
列不为空?如果是,则self.parent返回null是正常的。Nil我的意思是。

尝试向关联的每一侧添加属性的逆\u:

在父模型上:

 has_one :child, :inverse_of => :parent
在子模型上:

 belongs_to :parent, :inverse_of => :child
在这里,寻找“双向关系”:


希望有帮助

在我的脑海中,是否应该将“parent”大写为“parent”?我认为这应该是在类级别,我想访问与子类关联的类的实例。啊,是的,我认为你是对的。=)你是如何创造你的孩子的?控制器代码可能会有所帮助。子项是使用@parent.build\u child的等效项创建的。它没有设置为not NULL-但是这真的有区别吗?顺便说一下,我删除了attr\u accessible:child\u attributes行,它可以工作-语法错误?