Jason Shultz
Jason Shultz

Reputation: 970

How can I pass a nested json object to rails from angular

I have this:

$scope.create = function() {
    var theproperty = {
          businessName: this.businessName,
          streetAddress: this.streetAddress,
          city: this.city,
          state: this.state,
          zip: this.zip,
          mdu: this.mdu,
          units: this.units,
          content: this.content
    };

var propertywrap = {
      property: theproperty
    }

I sent that to the factory which passes it on to rails. Right now, def create just has this:

@property = Property.new(params[:property])

and then i have an if/else/end in case i get that far. But, until I can actually get it that far, I haven't worked on safe_params or anything yet. First things first, right?

The object that get's passed looks like this:

{"property":{"businessName":"test","streetAddress":"test thgis","city":"asdfqw4r","state":"qfa","zip":"asdfas","units":"asdfa","content":"asdfasdf"}}

And console log shows this:

Started POST "/properties" for 127.0.0.1 at 2014-06-27 13:02:25 -0600
Processing by PropertiesController#create as HTML
Parameters: {"property"=>{"businessName"=>"test from firefox", "streetAddress"=>"12 any st", "city"=>"clearfield", "state"=>"ut", "zip"=>"55445", "units"=>"adf",    "content"=>"asdfasdfasdf"}}
Completed 500 Internal Server Error in 1ms

But i'm getting a response back: ActiveModel::ForbiddenAttributesError

I even tried forming my object to pass this way:

var propertywrap = {
      property : {
        businessName: this.businessName,
        streetAddress: this.streetAddress,
        city: this.city,
        state: this.state,
        zip: this.zip,
        mdu: this.mdu,
        units: this.units,
        content: this.content
      }
    }

But I still got the same error back.

ActiveModel::ForbiddenAttributesError at /properties
====================================================

> ActiveModel::ForbiddenAttributesError

Am I doing this completely crazy? What should I be doing?

Based on an answer below, I changed the params and the table to use underscore instead of camelcase. So, now i'm passing:

{"property":{"business_name":"something her","street_address":"960 s 550 e","city":"sometown","state":"te","zip":"85121","units":"adf","content":"asdfasdf asdfasdf"}}

I'm still getting the same error, though.

Upvotes: 2

Views: 1136

Answers (1)

Artur Trzop
Artur Trzop

Reputation: 344

Probably the reason of issue is camelcase of params like businessName and streetAddress. On rails side this properties should be business_name and street_address.

You can use https://github.com/FineLinePrototyping/angularjs-rails-resource "By default we convert attribute names between underscore and camel case."

Upvotes: 1

Related Questions