如何用rails中的json更新nested_attributes?

时间:2013-08-22 10:15:28

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2 nested-attributes

我有

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

 class Sample < ActiveRecord::Base
    belongs_to :tests
 end

现在我按照以下方式创建新值

  

卷曲-H'内容类型:application / json'-H'接受:application / json'   -X POST http://localhost:3000/tests.json -d“{\”test \“:{\”name \“:\”xxxxxx \“,   \ “samples_attributes \”:[{\ “用户名\”:\ “YYYYYYY \”,\ “年龄\”:\ “25 \”}]}}“

它为测试创建了一个新值,它还在 sample 表中创建了一个条目,但在更新时会更新测试表,而在示例表中创建一个新条目。那我怎么能让它更新现在的条目?

请帮帮我。

1 个答案:

答案 0 :(得分:8)

您需要在散列中传递id以获取更新记录(view 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' }
  ]
}}