簡體   English   中英

如何用rails中的json更新nested_attributes?

[英]How to update the nested_attributes with json in rails?

我有

 class Test < ActiveRecord::Base
        has_many :samples
        accepts_nested_attributes_for :samples
 end

 class Sample < ActiveRecord::Base
    belongs_to :tests
 end

現在,當我創建新值如下

curl -H'Content-Type:application / json'-H'接受:application http://localhost:3000/tests.json X POST http://localhost:3000/tests.json -d“{\\”test \\“:{\\”name \\ “:\\”xxxxxx \\“,\\”samples_attributes \\“:[{\\”username \\“:\\”yyyyyyy \\“,\\”age \\“:\\”25 \\“}]}}”

它為測試創建了一個新值,它還在sample表中創建了一個條目,但在更新時更新了測試表,而在樣本表中創建了一個新條目。 那我怎么能讓它更新目前的條目?

請幫我。

您需要在散列中傳遞id以獲取更新記錄( 視圖API ):

class Member < ActiveRecord::Base   
  has_many :posts   
  accepts_nested_attributes_for :posts
end

如果哈希包含與已關聯記錄匹配的id密鑰,則將修改匹配記錄:

member.attributes = {
  name: 'Joe',
  posts_attributes: [
    { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
    { id: 2, title: '[UPDATED] other post' }
  ]
}

對於沒有id密鑰的每個哈希,將實例化新記錄。

params = { member: {
  name: 'joe', posts_attributes: [
    { title: 'Kari, the awesome Ruby documentation browser!' },
    { title: 'The egalitarian assumption of the modern citizen' }
  ]
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM