开发者

Can't access child's parent through has_one

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?


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.


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!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜