log*_*esh 2 ruby-on-rails nested-attributes ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2
我有
class Test < ActiveRecord::Base
has_many :samples
accepts_nested_attributes_for :samples
end
Run Code Online (Sandbox Code Playgroud)
和
class Sample < ActiveRecord::Base
belongs_to :tests
end
Run Code Online (Sandbox Code Playgroud)
现在,当我创建新值如下
curl -H'Content-Type:application/json'-H'Eccept:application/json'-X POST
http://localhost:3000/tests.json-d"{\"test \":{\"name \":\"xxxxxx \","samples_attributes\":[{\"用户名\ ":\" YYYYYYY\"\ "年龄\":\ "25 \"}]}}"
它为测试创建一个新值,它还在sample表中创建一个条目,但在更新时更新测试表,而在样本表中创建一个新条目.那我怎么能让它更新目前的条目?
请帮我.
小智 8
您需要传递id散列中的更新记录(视图API):
class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
end
Run Code Online (Sandbox Code Playgroud)
如果哈希包含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' }
]
}
Run Code Online (Sandbox Code Playgroud)
对于没有id密钥的每个哈希,将实例化新记录.
params = { member: {
name: 'joe', posts_attributes: [
{ title: 'Kari, the awesome Ruby documentation browser!' },
{ title: 'The egalitarian assumption of the modern citizen' }
]
}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2977 次 |
| 最近记录: |