2

我有

 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 'Accept: application/json' -X POST http://localhost:3000/tests.json-d "{\"test\":{\"name\":\"xxxxxx\", \"samples_attributes \":[{\"用户名\":\"yyyyyyy\",\"年龄\":\"25\"}]}}"

它为测试创建了一个新值,并且还在表中创建了一个条目,sample但是在更新它时会更新测试表,而它会在示例表中创建一个新条目。那么我怎样才能让它更新当前条目呢?

请帮我。

4

1 回答 1

8

您需要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' }
  ]
}}
于 2013-08-22T19:55:16.137 回答