activerecord 중첩 된 속성에 대한 prever_update 콜백에서 새로운 어린이를 처리하는 방법
-
19-09-2019 - |
문제
다른 모델 객체 (child)에 has_many 협회가있는 모델 객체 (부모라고하자)가 있습니다.
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
부모의 경우 이전 _update 콜백에 코드를 추가하여 어린이를 기반으로 계산 된 속성을 설정하고 싶습니다.
내가 실행 한 문제는 Method Parent.Update (id, atts)를 사용할 때 새로운 어린이를 위해 ATTS를 추가 할 때 ATTS 컬렉션에 추가 된 사람들이 이전에 사용할 수 없다는 것입니다. .
AcceptS_nested_attributes_for를 엉망으로 만들지 않고 새 것을 검색 할 수있는 방법이 있습니까?
해결책
당신이 묘사 한 것은 레일 2.3.2로 저에게 효과가 있습니다. 부모님의 자녀에게 올바르게 할당하지 않을 수 있다고 생각합니다. 업데이트 후 어린이가 업데이트됩니까?
accepts_nested_attributes_for는 질문에 사용 된대로 부모에게 child_attributes 작가를 만듭니다. 나는 당신이 업데이트하려는 느낌을 가지고 있습니다.
설명대로 귀하의 모델과 다음에 다음과 같은 이전 콜백을 사용하여 작동합니다.
before_update :list_childrens_names
def list_childrens_names
children.each{|child| puts child.name}
end
콘솔에서 이러한 명령 :
Parent.create # => Parent(id => 1)
Parent.update(1, :childrens_attributes =>
[{:name => "Jimmy"}, {:name => "Julie"}])
이 출력을 생성하십시오.
Jimmy
Julie
제휴하지 않습니다 StackOverflow