【问题标题】:Validation of child attributes based on a parent condition in Mongoid基于 Mongoid 中的父条件验证子属性
【发布时间】:2014-05-18 04:47:19
【问题描述】:

如果父文档中的属性为真或假,我正在尝试根据条件validate_presence_of 子属性。请在下面查看我的模型:

class Venue
  include Mongoid::Document

  field :name, type: String
  field :has_locations, type: Mongoid::Boolean

  embeds_many :locations
  accepts_nested_attributes_for :locations
end

还有子(嵌入式)模型。

class Location
  include Mongoid::Document

  field :city

  embedded_in :venue, inverse_of: :locations

  # Here I want to validate presence of :city, but only if
  # :has_locations in Venue is true
  validates_presence_of :city, if: ????

end

然后我有一个带有:has_locationsfields_for 复选框的表单,用于嵌套位置属性。我的视图和控制器都设置好了,我想我只是不明白如何在模型中进行这种子父条件验证。任何帮助表示赞赏!

【问题讨论】:

    标签: ruby-on-rails validation mongoid associations conditional


    【解决方案1】:

    经过更多的修改,我能够像这样实现所需的功能,不确定是否是最好的方法,但它就是这样,尽管现在还有一个自定义错误消息的新问题。我的模型现在看起来像这样:

    class Venue
      include Mongoid::Document
    
      field :name, type: String
      field :has_locations, type: Mongoid::Boolean
    
      embeds_many :locations
      accepts_nested_attributes_for :locations, reject_if: :no_location_required
    
      private
    
      def no_location_required
        has_locations == false
      end
    end
    

    class Location
      include Mongoid::Document
    
      field :city
    
      embedded_in :venue, inverse_of: :locations
    
      validates_presence_of :city
    
    end
    

    现在这似乎可行,但由于某种原因显示的验证错误消息是通用的:“位置无效”。我希望它返回“需要城市”。我尝试在en.yml 中处理错误消息,但至今无济于事。

    【讨论】:

      【解决方案2】:

      您可以使用validates_associated。这将验证关联的对象是否都有效。

      所以这会转到您的父模型,例如:

      class Venue
       include Mongoid::Document
      
       field :name, type: String
       field :has_locations, type: Mongoid::Boolean
      
       embeds_many :locations
       accepts_nested_attributes_for :locations
      
       #validate the associated locations if has_locations is checked (or true)
       validates_associated :locations, if: Proc.new { |venue| venue.has_locations }
      end
      

      现在,添加您想在位置模型中添加的任何常规验证:

      class Location
       include Mongoid::Document
      
       field :city
      
       embedded_in :venue, inverse_of: :locations
      
       # Here I want to validate presence of :city
       validates_presence_of :city
       #Never use validates_associated :venue here if we have already use it in the associated model, otherwise will be a circular dependency and cause infinite recursion.
      end
      

      【讨论】:

      • 谢谢 Manoj!我尝试了您的方法,但它不起作用,它会尝试验证嵌套属性而不管条件如何,因此检查或取消检查 :has_locations 无效,无论哪种方式都可以进行验证。嗯……
      • 谁能提供上述解析的猫鼬表示?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2021-06-17
      • 2019-06-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      相关资源
      最近更新 更多