草庐IT

ruby-on-rails - rails : How to test if an attribute of a class object is required in the model policy?

coder 2025-05-19 原文

简单地说,我有一个模型用户,其中包含名称、电子邮件和评论作为属性。

validates_presence_of :name
validates_presence_of :email

所以“姓名”和“电子邮件”是必需的,但不是“评论”。

my_user = User.new

我想找到一种方法来测试像 my_user.name.required?或 User.name.required?类似的东西。

我的目标是创建一个表单,并根据该项目是否设置为“validates_presence_of”,将特定类动态添加到表单项目 span 或 td

我试图搜索它,但没有找到任何相关信息。有没有简单的方法可以做到这一点?

谢谢

最佳答案

没有一个方法可以调用来处理这个问题,但是 this post讨论如何创建一个辅助方法来实现您所追求的目标。

module InputHelper 
  def required?(obj, attribute)
    target = (obj.class == Class) ? obj : obj.class
    target.validators_on(attribute)
          .map(&:class)
          .include?(ActiveModel::Validations::PresenceValidator)
  end
end

关于ruby-on-rails - rails : How to test if an attribute of a class object is required in the model policy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829996/

有关ruby-on-rails - rails : How to test if an attribute of a class object is required in the model policy?的更多相关文章

随机推荐