9

当使用accepts_nested_attributes_for时,我想传递“child”而不是传递“child_attributes”。我很确定如果我在我的控制器中放入很多逻辑来创建记录和子项,我可以做到这一点。但是,为了使我的控制器保持清洁和逻辑,在这种情况下,模型,我想知道如何在执行 POST 或 PUT 时切换 rails 3 以使用此语法。

{
  "name": "test",
  "child_attributes": [
    {
      "id": 1,
      "name": "test_child_update"
    },
    {
      "name": "test_child_create"
    }
}

相当

{
  "name": "test",
  "child": [
    {
      "id": 1,
      "name": "test_child_update"
    },
    {
      "name": "test_child_create"
    }
}
4

2 回答 2

4

显然,这是做不到的。

于 2012-11-12T22:51:47.243 回答
2

后缀对_attributesJSON 请求和响应没有任何价值,但要在模型层中去掉它,您必须对 ActiveRecord 进行修补。每个人都讨厌猴子修补 ActiveRecord 关系。

How about doing it in the controller layer?

@comment = Comment.new(attributify(:comment))

# snip

# ApplicationController

def attributify()
  # Now I'll go and write this!
end

Edit: Done. The controller mixin is here: https://gist.github.com/johncant/6056036

于 2013-07-22T15:11:44.167 回答