9

When using accepts_nested_attributes_for, instead of having to pass "child_attributes", I'd like to pass "child". I'm pretty sure if I put a lot of the logic in my controller to create the the records and children, I could accomplish this. However, in an effort to keep my controllers clean and logic where it should be, the model in this case, I'd like to know how to switch rails 3 around to use this syntax when doing a POST or PUT.

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

Rather

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

2 に答える 2

4

明らかに、これはできません。

于 2012-11-12T22:51:47.243 に答える
2

サフィックスは JSON リクエストとレスポンスに何の_attributes価値も追加しませんが、モデル レイヤーでそれを取り除くには、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

于 2013-07-22T15:11:44.167 に答える