2013-05-03 1 views
1

레일에서 모델에 update_attributes을 사용하면 association_attributes을 기반으로하는 중첩 모델이 만들어집니다. 중첩 모델을 제자리에 업데이트하는 관용적 인 방법이 있습니까?Rails ActiveRecord는 위치에 중첩 된 특성을 업데이트합니다.

Message.rb : 예를 들어

attr_accessible :recipient_attributes 
has_one :recipient 
accepts_nested_attributes_for :recipient 

Recipient.rb

belongs_to :message 
# has an name fied 
# has an email field 

받는 사람

r = Recipient.create 
r.create_recipient name: "John Smith", email: "[email protected]" 
r.update_attributes recipient_attributes: {email: "[email protected]"} 
r.recipient.name # nil <-- this creates a NEW recipient, so the name is nil 
r.recipient.email # [email protected] 

대신, 나는 r.recipient이 동일한 것으로 예상 수신자 기록이지만 새 이메일이 있습니다.

답변

5

업데이트하려면 중첩 된 특성의 ID를 전달해야합니다. ID가 없으면 새 레코드로 간주됩니다.

현실적으로 물론, 그것은 형태 일 것입니다. 귀하의 예를 들어 :

john = r.create_recipient name: "John Smith", email: "[email protected]" 
r.update_attributes recipient_attributes: {id: john.id, email: "[email protected]"} 
+0

오, 그 의미가 톤 - has_many 협회와 함께 일 해왔다 분명했을 것입니다. 감사! –

+0

내가 +100이 될 수 있다면, 나는 그렇게 할 것이다. 흥미로운 측면은 제가 API를 사용하고 있다는 것입니다. 그래서 이것은 아직 형태가 아닙니다. 나는 그것을 추론하고 그것이 존재한다면 매개 변수에 그것을 추가해야했다. – Mizmor