Rails accepts_nested_attributes_for child doesn't have parent set when validating

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

    You cannot do this because in-memory child doesn't know the parent its assigned to. It only knows after save. For example.

    child = parent.build_child
    parent.child # => child
    child.parent # => nil
    
    # BUT
    child.parent = parent
    child.parent # => parent
    parent.child # => child
    

    So you can kind of force this behavior by doing reverse association manually. For example

    def child_with_inverse_assignment=(child)
      child.parent = self
      self.child_without_inverse_assignment = child
    end
    
    def build_child_with_inverse_assignment(*args)
      build_child_without_inverse_assignment(*args)
      child.parent = self
      child
    end
    
    def create_child_with_inverse_assignment(*args)
      create_child_without_inverse_assignment(*args)
      child.parent = self
      child
    end
    
    alias_method_chain :"child=", :inverse_assignment
    alias_method_chain :build_child, :inverse_assignment
    alias_method_chain :create_child, :inverse_assignment
    

    If you really find it necessary.

    P.S. The reason it's not doing it now is because it's not too easy. It needs to be explicitly told how to access parent/child in each particular case. A comprehensive approach with identity map would've solved it, but for newer version there's :inverse_of workaround. Some discussions like this one took place on newsgroups.

提交回复
热议问题