1

许多教程介绍了在使用 AngularJS 时在 Rails 模型中的简单嵌套。但我花了将近一周的时间尝试将多态关系实现到角度控制器中。我的组织包含多态电话、电子邮件等。我尝试保存新组织。这是我的控制器:

    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) ->
)

accepts_nested_attributes_for :phones 在我的 Rails 模型和 params.require(:organization).permit(:id, :title, :description, phones_attributes:[:id, :number]) 控制器中有。在保存时,我得到了控制台的响应:

由 OrganizationsController#create 作为 JSON 参数处理:{"organization"=>{"title"=>"test212", "phones"=>[{"number"=>"32323"}]}} 不允许的参数:电话

知道如何解决吗?

4

2 回答 2

1

您的问题是您在后端控制器中允许“phones_attributes”:

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

但是您在前端控制器中发送“电话”:

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

因此,您会在服务器接收的 JSON 中看到“电话”属性:

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

它正确地告诉你这是不允许的:

Unpermitted parameters: phones

解决这个问题的最好方法是让前端控制器发送“phones_attributes”而不是“phones”:

    ... phones_attributes: [number: $scope.phone.number] ...
于 2014-05-23T17:04:15.987 回答
0

这可能是 rails 4 中的一个强大的参数问题。在用于组织的 rails 控制器中,您应该有一个类似以下的方法

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

然后在 create 方法中你应该:

def create
    respond_with Organization.create(org_params)
end
于 2013-09-09T20:40:22.187 回答