Rails accepts_nested_attributes_for child doesn't have parent set when validating

前端 未结 4 1678
情书的邮戳
情书的邮戳 2021-02-04 12:50

I\'m trying to access my parent model in my child model when validating. I found something about an inverse property on the has_one, but my Rails 2.3.5 doesn\'t recognize it, s

4条回答
  •  情歌与酒
    2021-02-04 13:13

    I had basically the same problem with Rails 3.2. As suggested in the question, adding the inverse_of option to the parent's association fixed it for me.

    Applied to your example:

    class Parent < AR
      has_one :child, inverse_of: :parent
      accepts_nested_attributes_for :child
    end
    
    class Child < AR
      belongs_to :parent, inverse_of: :child
      validates_presence_of :name, :if => :some_method
    
      def some_method
        return self.parent.some_condition   # => undefined method `some_condition' for nil:NilClass
      end
    end
    

提交回复
热议问题