基于Mongoid中的父条件验证子属性

时间:2014-04-05 21:29:04

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

如果父文档中的属性为true或false,我会根据条件尝试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的复选框,用于嵌套的位置属性。我的观点和控制器都已设置好,我想我只是不了解如何在模型中进行这种子父项条件验证。任何帮助赞赏!

2 个答案:

答案 0 :(得分: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中使用错误消息,但到目前为止无济于事。

答案 1 :(得分:0)

您可以使用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