【问题标题】:Ruby on Rails: validate the presence and existence of an associationRuby on Rails:验证关联的存在和存在
【发布时间】:2016-06-28 03:38:19
【问题描述】:

我想知道 Rails 中是否有一种方法可以验证关联的存在(数据库中的 AND 存在)而不如果可能的话使用任何额外的 gem(即关联的“belongs_to”对象在数据库中,保存前有效)。

validates_presence_of 不起作用,因为您可以使用新创建且未保存的对象。

我对@9​​87654322@ gem 了如指掌,但我想尽可能避免使用它。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    您可以将validates_associatedvalidates_presence_of 结合使用。

    validates_associated 将对关联模型(您必须在该模型中定义)运行验证。

    validates_presence_of 验证关联的存在。

    编辑

    解决您的评论:不是专门验证数据库中存在的常见场景,但您可以这样做:

    validate :association_exists
    
    def association_exists
      # query database for the association record and return true if it exists
      # self is model instance inside this method
    end
    

    【讨论】:

    • 如果关联对象有效且存在但未保存怎么办
    • 如何强制执行 belongs_to 的完整性不是一个常见的场景?也许我没有让自己足够清楚......对我来说,这似乎是我会在每个模型中做的事情。
    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多