Altonymous
Altonymous

Reputation: 783

Rails 3 How can I allow nested attributes to be passed without the _attributes designation

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"
    }
}

Upvotes: 9

Views: 811

Answers (2)

user1158559
user1158559

Reputation: 1953

The _attributes suffix adds no value to JSON requests and responses, but to get rid of it in the model layer, you would have to monkey patch ActiveRecord. Everyone hates monkey-patching ActiveRecord relations.

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

Upvotes: 2

Altonymous
Altonymous

Reputation: 783

Evidently, this can't be done.

Upvotes: 4

Related Questions