Search code examples
ruby-on-railsrestmodelnested-attributesnested-resources

Rails - Creating a model and its nested resources


I'm trying to create a Gallery model and its has_many associations by passing the following to create.

[
  {
    "title":"Some Titler",
    "description":"",
    "date":"18-3-2012",
    "photographs":[
      {
        "title": "Some Title",
        "camera": "Canon 600D"
      },
      {
        "title": "Some Other Title",
        "camera": "Canon 600D"
      }
    ]
  }
]

Without the nested photographs array, it works fine, but with it, I get an error:

Photograph(#70242279271180) expected, got Hash(#70242248401160)

What is wrong with the syntax?

class Gallery < ActiveRecord::Base
  attr_accessible :date, :description, :published, :title


  has_many :photographs
  accepts_nested_attributes_for :photographs

end

Solution

  • Change

     "photographs":[]
    

    to

     "photographs_attributes":[]