AngularJS to Rails MassAssignmentSecurity::Error

AngularJS to Rails MassAssignmentSecurity::Error

本文关键字:Error MassAssignmentSecurity Rails to AngularJS      更新时间:2023-09-26

在Rails中使用AngularJS时,我在更新时不断收到MassAssignmentSecurity错误。我知道这是由于将诸如"created_at"answers"updated_at"之类的属性与数据一起传递。

为了解决这个问题,我一直在构建一些json,它只传递表单中的属性。这确实会在整个程序中创建更多的维护。

有更好的方法吗?

这里有一个例子:

AngularJS

  $scope.contruct_json = ->
    {
      name: $scope.client.name
      surname: $scope.client.surname
    }

  # --------------------------------------------------------------------------------
  # Update
  # --------------------------------------------------------------------------------
  $scope.update = ->
    Client.update
      id: $stateParams['id']
    ,
      client: $scope.contruct_json()
    , (response) ->
      $location.path "/clients/#{$stateParams['id']}"

更新

将我的AngularJS代码更改为此

  # Remove keys from hash to make it acceptable for Rails to update
  $scope.remove_keys = (hash) ->
    new_hash = {}
    angular.forEach(hash, (value,key) ->
      if(key!='id' && key!='created_at' && key!='updated_at')
        new_hash[key]=value
    ,  new_hash)
    return new_hash
  # --------------------------------------------------------------------------------
  # Update
  # --------------------------------------------------------------------------------
  $scope.update = ->
    Client.update
      id: $stateParams['id']
    ,
      client: $scope.remove_keys($scope.client)
    , (response) ->
      $location.path "/clients/#{$stateParams['id']}"

也许您应该考虑允许使用attr_accessibleClient模型上的属性进行批量分配?

无论您如何分配属性,都需要在模型中将它们声明为可批量分配。尝试以下操作:

class Client < ActiveRecord
    attr_accessible :created_at, :updated_at # Any attributes you need to make mass-assignable
end