Stan
Stan

Reputation: 1287

Polymorphic rails relations in Angularjs application

Many tutorials cover the simple nesting in Rails model when working with AngularJS. But I spent almost a week trying to implement polymorphic relations into angular controllers. I have organization with polymorphic phones, emails, etc. I try to save new Organization. Here is my controller:

    angular.module('GarageCRM').controller 'NewOrganizationsCtrl', ($scope, $location, Organization) ->

  $scope.organization = {}
  $scope.organization.phones_attributes = [{number: null}]

  $scope.create = ->
    Organization.save(
      {}
    , organization:
        title: $scope.organization.title
        description: $scope.organization.description
        phones:
          [number: $scope.phone.number]
  # Success
, (response) ->
    $location.path "/organizations"

  # Error
, (response) ->
)

I have accepts_nested_attributes_for :phones in my rails model and params.require(:organization).permit(:id, :title, :description, phones_attributes:[:id, :number]) in controller. While saving I have response from console:

Processing by OrganizationsController#create as JSON Parameters: {"organization"=>{"title"=>"test212", "phones"=>[{"number"=>"32323"}]}} Unpermitted parameters: phones

Any idea how to fix it?

Upvotes: 1

Views: 340

Answers (2)

jsanders
jsanders

Reputation: 599

Your problem is that you are permitting "phones_attributes" in your back-end controller:

... phones_attributes:[:id, :number] ...

But you are sending "phones" in your front-end controller:

... phones: [number: $scope.phone.number] ...

So you see the "phones" attribute in the JSON the server receives:

JSON Parameters: ... "phones"=>[{"number"=>"32323"}] ...

And it correctly tells you it isn't permitted:

Unpermitted parameters: phones

The best way to fix this is to make the front-end controller send "phones_attributes" instead of "phones":

    ... phones_attributes: [number: $scope.phone.number] ...

Upvotes: 1

Jason Carty
Jason Carty

Reputation: 1247

This could be a strong paramaters issue from rails 4. In the rails controller for organization you should have a method like the follwing

private
def org_params
    params.require(:organization).permit(:id, :name, :somethingelse, :photos_attributes[:id, :name, :size ])
end

And then in the create method you should:

def create
    respond_with Organization.create(org_params)
end

Upvotes: 0

Related Questions