【问题标题】:Ruby on Rails: How to limit the key for Hash Fields in Mongoid?Ruby on Rails:如何限制 Mongoid 中哈希字段的键?
【发布时间】:2021-05-20 03:25:20
【问题描述】:

例如,我想只允许字段url 使用密钥url

class Person
  include Mongoid::Document
  field :first_name
  field :url, type: Hash
end

我想要这份工作

def set_vals
  self.first_name = 'Daniel'
  self.url = {'home_page' => 'http://www.homepage.com'}
  save
end

这失败了

def set_vals
  self.first_name = 'Daniel'
  self.url = {'unknown' => 'http://www.homepage.com'}
  save
end

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    添加模型验证,检查密钥,如果存在不需要的密钥,则向模型添加错误。

    【讨论】:

    • 具体怎么做?
    猜你喜欢
    • 2014-01-04
    • 2010-12-06
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多