【问题标题】:How to prevent any in an array of terms in a field in a model in rails?如何防止rails模型中字段中的术语数组中的任何一个?
【发布时间】:2020-09-04 14:32:40
【问题描述】:

假设我们不想让用户名是banned = ['badWordOne', 'otherbadword', 'notthiseither']中的任何一个

我们如何做到这一点?

我尝试使用acceptance 并直观地将accept 更改为reject,但这不起作用:

banned_names = ['badWordOne', 'otherbadword', 'notthiseither']

validates :username, acceptance: { reject: banned_names }, if: :username 

【问题讨论】:

    标签: ruby-on-rails rails-models


    【解决方案1】:

    我想我在exclusion找到了答案

    banned_names = ['badWordOne', 'otherbadword', 'notthiseither']
    
    validates :username, exclusion: { in: banned_names }, if: :username 
    
    

    【讨论】:

    • 是的,这会起作用,但是“badwordone”是可接受的用户名吗? “1badWordOne”怎么样?
    • @engineersmnky 好点!就我而言,我只需要禁止确切的术语,但如果其他人在这里找到了自己的方式,那么了解如何禁止包含任何不需要的单词的术语可能会非常有用。 (我的用例只是停止重复路由,因为某些路由看起来像domain.com/:username。因此,如果有人将他们的用户名设置为“用户”或“产品”,例如(因为这与某些资源的路由冲突) . 我很想知道如何禁止在数组中包含任何子字符串的术语
    • 可能想看看format验证
    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多