Rails accepts_nested_attributes_for child doesn't have parent set when validating

前端 未结 4 1730
情书的邮戳
情书的邮戳 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:01

    I had a similar problem: Ruby on Rails - nested attributes: How do I access the parent model from child model

    This is how I solved it eventually; by setting parent on callback

    class Parent < AR
      has_one :child, :before_add => :set_nest
      accepts_nested_attributes_for :child
    
    private
      def set_nest(child)
        child.parent ||= self
      end
    end
    

提交回复
热议问题