无法通过 has_one 访问子级的父级

发布于 2024-10-10 12:43:40 字数 590 浏览 0 评论 0原文

我这里有一个令人困惑的问题。我有两个模型,具有 has_one 关系。我有一个使用 fields_for 创建子实例的表单。然而,当我尝试从子模型访问父模型时,它只得到一个零。

我试图提供以下问题的简洁明了的示例:

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

为什么关系返回为零?

I have a confusing problem here. I have two models, with a has_one relationship. I have a form that uses fields_for to create the child instance. However, when I try and access the parent from the child model it only gets a nil.

I've tried to provide a concise and simple example of the issue below:

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

The problem is that the parent.name.equals?("mum") returns an error:

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

Why is the relationship being returned as nil?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

番薯 2024-10-17 12:43:40

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

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

编辑:在您的数据库中,您确定childs表中的parent_id列不为空吗?如果是,那么 self.parent 返回 null 是正常的。我的意思是零。

I'm not sure, but try with self.parent.name.equals?("mum")

self may be implicit, so this might not be your solution.

EDIT: In your database, are you sure the column parent_id in childs table is not null ? If it is, then it's normal that self.parent returns null. Nil I mean.

青萝楚歌 2024-10-17 12:43:40

尝试将属性 inverse_of 添加到关联的每一侧:

在父模型上:

 has_one :child, :inverse_of => :parent

在子模型上:

 belongs_to :parent, :inverse_of => :child

在这里,查找“双向关系”:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

希望有帮助!

Try adding the attribute inverse_of to each side of the association:

on the Parent model:

 has_one :child, :inverse_of => :parent

on the Child model:

 belongs_to :parent, :inverse_of => :child

Here, look for "Bi-Directional Relationships":
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文