首页 > 解决方案 > Rails 不断拒绝字符串参数作为枚举

问题描述

我正在从前端子化我的参数,这就是到达我的后端的内容 Started PUT "/api/admin/deputados_perfis/50" for 127.0.0.1 at 2019-03-27 18:38:49 +0000

  Parameters: {"deputado"=>{"id"=>"50", "nome"=>"Ademir Menezes", "ativo"=>"false", "sexo_feminino"=>"false", "partido"=>"PSD", "deputado_rede_social_attributes"=>{"0"=>{"$$hashKey"=>"object:76", "tipo"=>"youtube", "conteudo"=>"14515414515"}}, "deputado_perfil_attributes"=>{"id"=>"239", "deputado_id"=>"50", "nome_completo"=>"khjkghjkfj", "biografia"=>"utotuiyuiytiittyiutyi", "site"=>"", "telefones"=>"", "gabinete"=>"", "created_at"=>"2019-03-27T14:54:35.792-03:00", "updated_at"=>"2019-03-27T14:55:23.388-03:00"}}, "id"=>"50"}

但我的服务器拒绝更新,因为'youtube' is not a valid tipo

我正在使用 Rails 5.1.4 和 Ruby 2.3.7

我的相关方法

module Api
    module Admin
        class DeputadosPerfisController < Api::Admin::PrivateController
            before_action :set_deputado, only: %i[show edit update destroy]

            def update
                @deputado.update(deputado_params)
                @mensagem = 'Perfil do deputado criado com sucesso'
                render json: { mensagem: @mensagem, codigo: 1, deputado_id: @deputado.id }, status: 201
            end

            private
            def set_deputado
                @deputado = ::AlegoShared::Public::Deputado.includes(:deputado_perfil, :deputado_rede_social).find params[:id]
            end

            def deputado_params
                params.require(:deputado).permit(:id, deputado_perfil_attributes: [:id, :nome_completo, :biografia, :site, :foto, :gabinete, :telefones, :deputado_id], 
                    deputado_rede_social_attributes: [:id, :tipo, :conteudo, :deputado_id])
            end
        end
    end
end

我在模式中的表

  create_table "deputado_rede_sociais", force: :cascade do |t|
    t.integer "deputado_id", null: false
    t.string "conteudo", null: false
    t.integer "tipo", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["deputado_id"], name: "idx_deputado_rede_sociais_deputados"
  end

我的模特

module Portal
    class DeputadoRedeSocial < ApplicationRecord
       enum tipo: [:email, :facebook, :instagram, :youtube, :twitter, :outros]

        validates_presence_of :deputado_id, :conteudo, :tipo
    end
end

我的观点片段

            <h3>Redes sociais</h3>

            <div ng-repeat="redeSocial in vm.deputado.deputado_rede_social">
                <label show-erros class="field-12 form-texto">
                    <span class="label">Tipo de rede social</span>
                    <select name="ano" ng-model="redeSocial.tipo" ng-options="obj.key as obj.value for obj in vm.tiposRedeSocial track by obj.key"  ng-required="true">
                        <option disabled value="">Selecione</option>
                    </select>
                    <div ng-messages="vm.form.redeSocial.tipo.$error" class="form--erro__bloco">
                        <div ng-message="required">Tipo de rede social é obrigatória.</div>
                    </div>
                </label>

                <label show-erros class="field-12 form-texto">
                    <span class="label">Endereço</span>
                    <input name="biografia" ng-model="redeSocial.conteudo" ng-required="true" autocomplete="off" />
                    <div ng-messages="vm.form.data.$error" class="form--erro__bloco">
                        <div ng-message="required">Conteúdo é obrigatório.</div>
                    </div>
                </label>

                <a ng-click="vm.removerRedeSocial">Remover rede social</a>
            </div>

            <a ng-click="vm.adicionarRedeSocial()">Adicionar rede social</a>

我的 AngularJS 控制器

;(function () {
  'use strict'

  angular.module('app.admin.deputados')
    .controller('DeputadosFormController', DeputadosFormController)

  DeputadosFormController.$inject = ['$state', '$scope', 'deputado', 'tipos', 'SweetAlert', '$stateParams', 'toastr']
  function DeputadosFormController ($state, $scope, deputado, tipos, SweetAlert, $stateParams, toastr) {
    var vm = this
    vm.deputado = deputado
    vm.salvar = salvar
    vm.adicionarRedeSocial = adicionarRedeSocial

    function adicionarRedeSocial () {
      vm.deputado.deputado_rede_social.push({})
    }

    function salvar () {
      $scope.$broadcast('show-errors-check-validity')
      if (vm.form.$valid) {
        vm.deputado['deputado_rede_social_attributes'] = vm.deputado['deputado_rede_social']
        vm.deputado['deputado_perfil_attributes'] = vm.deputado['deputado_perfil']
        delete vm.deputado['deputado_rede_social']
        delete vm.deputado['deputado_perfil']
        vm.deputado.$update().then(function (result) {
          var mensagem = result.mensagem || 'Perfil do deputado criado com sucesso.'
          $state.go('admin.deputados_show', {
            id: result.deputado_id
          })
          toastr.success(mensagem)
        }, function (error) {
          toastr.error(error.data.mensagem)
        })
      } else {
        toastr.error('Preencha todos os campos obrigatórios')
      }
    }
  }
})()

我的数据服务

;(function () {
  'use strict'

  angular.module('app.base.admin')
    .factory('AdminDeputadosDataService', ['$resource', 'transformToFormData', function ($resource, transformToFormData) {
      var resource = $resource(
        API_HOST + '/api/admin/deputados_perfis/:id',
        { id: '@id' },
        {
          update: {
            method: 'PUT',
            transformRequest: function (data) {
              return transformToFormData.transform('deputado', data)
            },
            headers: { 'Content-Type': undefined }
          },
          query: {
            isArray: true,
            interceptor: {
              response: function (response) {
                response.resource.$totalLinhas = response.headers('TotalLinhas')
                return response.resource
              }
            }
          },
      return resource
    }])
})()

我期待保存我的记录。

标签: ruby-on-railsangularjsactiverecord

解决方案


推荐阅读