使用包含验证数组元素包含:{ in: array } [英] validates array elements inclusion using inclusion: { in: array }

查看:44
本文介绍了使用包含验证数组元素包含:{ in: array }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 acts-as-taggable-on gem 在这样的 User 模型上填充用户兴趣

I use acts-as-taggable-on gem to populate a user interests on a User model like this

# User.rb
acts_as_taggable
acts_as_taggable_on :interests

当我填充 interest_list 数组时,我需要检查给定的值是否与常量数组匹配,以确保这些是可接受的值,就像这样

As I populate the interest_list array, I need to check that the given values matches against a constant array to make sure these are accepted values, something like this

VALID_INTERESTS = ["music","biking","hike"]
validates :interest_list, :inclusion => { :in => VALID_INTERESTS, :message => "%{value} is not a valid interest" }

上面的代码返回以下错误

The code above returns the following error

@user = User.new
@user.interest_list = ["music","biking"]
@user.save
=> false …. @messages={:interest_list=>["music, biking is not a valid interest"]}

我可以看到包含没有意识到它应该遍历数组元素而不是 s 考虑为一个普通字符串,但我不确定如何实现这一点.有什么想法吗?

I can see the inclusion doesn't realize it should iterate over the array elements instead of s considering as a plain string but I'm not sure how to achieve this. Any idea?

推荐答案

标准包含验证器不适用于此用例,因为它会检查相关属性是否是给定数组的成员.您想要的是检查数组的每个元素(属性)是否是给定数组的成员.

The standard inclusion validator will not work for this use case, since it checks that the attribute in question is a member of a given array. What you want is to check that every element of an array (the attribute) is a member of a given array.

为此,您可以创建一个自定义验证器,如下所示:

To do this you could create a custom validator, something like this:

VALID_INTERESTS = ["music","biking","hike"]
validate :validate_interests

private

def validate_interests
  if (invalid_interests = (interest_list - VALID_INTERESTS))
    invalid_interests.each do |interest|
      errors.add(:interest_list, interest + " is not a valid interest")
    end
  end
end

通过计算这两个数组的差值,我得到了 interest_list 中不在 VALID_INTERESTS 中的元素.

I'm getting the elements of interest_list not in VALID_INTERESTS by taking the difference of these two arrays.

我还没有真正尝试过这段代码,所以不能保证它会起作用,但我认为解决方案看起来像这样.

I haven't actually tried this code so can't guarantee it will work, but the solution I think will look something like this.

这篇关于使用包含验证数组元素包含:{ in: array }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆