2012-08-10 60 views
6

当使用accept_nested_attributes_for,而不是必须通过“child_attributes”,我想通过“孩子”。我非常确定,如果我在控制器中添加了很多逻辑来创建记录和子项,我可以完成此操作。然而,为了保持控制器的清洁和逻辑性,在这种情况下,我想知道如何在执行POST或PUT时切换rails 3以使用此语法。Rails 3我怎样才能允许嵌套属性传递没有_attributes指定

{ 
    "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" 
    } 
} 
+1

我可以问你为什么要改变这个? – Robin 2012-08-10 15:46:55

+1

这个约定是有原因的,因为'child'属性实际上是指'Child'对象的集合,而不是'Child'对象的属性。 'child_attributes'属性用于阐明意图。 – PinnyM 2012-08-10 16:55:40

+0

我要在这里跋涉。传入的对象的类型应该足以确定意图。另外,由于JSON中没有类,所以使用'_attributes'实际上并没有清除任何东西。 – user1158559 2013-07-22 15:00:10

回答

4

显然,这无法做到的。

+0

我认为你是Stack中唯一承认无法完成的事情 – 2017-04-27 18:47:36

1

_attributes后缀不会为JSON请求和响应添加任何值,但要在模型层中删除它,您必须猴子修补程序ActiveRecord。每个人都讨厌修补猴子的ActiveRecord关系。

如何在控制器层做到这一点?

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

# snip 

# ApplicationController 

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

编辑:完成。控制器混合在这里:https://gist.github.com/johncant/6056036