【问题标题】:Rails presence validation didn't working in params key as arrayRails 存在验证在 params 键中作为数组不起作用
【发布时间】:2016-10-21 12:30:05
【问题描述】:

我在测试失败时遇到了这个问题,因为验证存在:true 不起作用。我想知道为什么它没有触发。所以,这是我拥有的代码:

控制器中的简单更新

def update
   person = Person.find_by( params[:id] )

   if person.update( params_person )
      render json: {}, status: :ok
   else
      render json: person.errors, status: :422
   end
end

def params_person
  params.require( :person ).permit( :firstname, :lastname, ... , hobbies: [] )
end

hobbies: [] 是一个字符串数组,例如 ['playing dota', 'basketball', 'coding', ... ]

人物模型

class Person < ActiveRecord::Base
  ...
  validates :hobbies, presence: true
  ...
end

如果我做了一个请求

{ ...
  ...
  hobbies: nil/'',
  ...
  ...
}

验证仍然通过,没有更新爱好作为数据nil/''

更新

describe '#update' do
    let( :user ) { create( :user ) }

    fcontext 'when params missing' do
      before do
        put :update, id: person.id,
            person: {
              ....,
              ....,
              hobbies: nil 
            }
      end

      it 'respond an error message' do
        expect( response_body ).to include( "Hobbies can't be blank" )
      end

      it { expect( response ).to have_http_status( 422 ) }
    end

【问题讨论】:

  • 你能发布你的测试吗?
  • @CdotStrifeVII 帖子已更新 .. 谢谢!
  • 您在测试中发送用户 {},但控制器使用人员。
  • 对不起。我修改它应该是人@eagleeye。

标签: ruby-on-rails ruby validation strong-parameters


【解决方案1】:

当您将hobbies: [] 放入strong_params 定义中,然后继续将标量传递给hobbies(您的nil 在那里),强参数将不允许它,因此不会在更新。

要验证这一点,请检查该测试中的 params_person

【讨论】:

  • 但是空字符串为什么它的作用相同呢?
  • @PepengA.: 因为它也是一个标量。
  • 那么,如何触发验证?我应该创建一个自定义验证器来检查爱好数组是否有值吗?
  • @PepengA.: 尝试传递空数组
  • 我已经这样做了,但它仍然没有触发验证。这就是为什么我不知道如何验证它。
猜你喜欢
  • 1970-01-01
  • 2017-01-08
  • 2013-05-27
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
相关资源
最近更新 更多