Ruby Rails根据保存的记录而不是编辑的记录验证是否存在

Ruby Rails根据保存的记录而不是编辑的记录验证是否存在,ruby,ruby-on-rails-3,activerecord,Ruby,Ruby On Rails 3,Activerecord,我有三种型号,型号1、型号12和型号2。Model1有许多model2到Model12 我必须验证model2到model12的存在性 当我试图保存model1的编辑记录时,rails正在保存没有model2的记录。只有当model1中已经存在的DB条目没有model2信息时,验证才会失败 class model1 < ActiveRecord::Base has_many :model12, :dependent => :destroy, :include => [:mo

我有三种型号,型号1、型号12和型号2。Model1有许多model2到Model12

我必须验证model2到model12的存在性

当我试图保存model1的编辑记录时,rails正在保存没有model2的记录。只有当model1中已经存在的DB条目没有model2信息时,验证才会失败

class model1 < ActiveRecord::Base
  has_many :model12, :dependent => :destroy, :include => [:model]
  has_many :model2, :through => :model12, :uniq => true

  validates_presence_of :model12, :message => "must be present"
这也不起作用

我猜在我的例子中,rails是在检查保存的记录而不是未保存的记录。 这就是为什么当已经保存的记录有model2而未保存的记录没有model2时,验证不会失败。但当保存的记录没有model2,而未保存的记录也没有model2时,它会失败


如果我的问题不清楚,请告诉我。

我找到了解决问题的方法

我在复选框中有model2。当我取消选中所有选中的Model2并提交表单时。因为我使用的是嵌套属性,所以它将旧的未经检查的Model2标记为销毁,而这种销毁将在之前的保存和验证运行之后发生

因此rails发现存在一些Model2,因此没有验证错误

class model1 < ActiveRecord::Base

  has_many :model12, :dependent => :destroy, :include => [:model]
  has_many :model2, :through => :model12, :uniq => true

  accepts_nested_attributes_for :model2,
    :allow_destroy => true,
    :reject_if => proc {|m| m.blank? }

  validate :must_have_one_model2

  def must_have_one_model2
    errors.add(:model2s, 'must have one model2') if model12s_count_valid?
  end

  def model12s_count_valid?
    model12s.reject(&:marked_for_destruction?).count >= 1
  end
end
classmodel1:destroy,:include=>[:model]
有多个:model2,:through=>:model12,:uniq=>true
接受:model2的\u嵌套\u属性\u,
:allow_destroy=>true,
:reject_if=>proc{m|m.blank?}
验证:必须有一个模型2
def必须有一个型号2
错误。如果model12s\u计数有效,是否添加(:model2s,'必须有一个model2')?
结束
def型号12S\U计数是否有效?
型号12S.拒收(&:标记为销毁?)。计数>=1
结束
结束

多亏了les hill的帖子

我想你应该为此添加一个自定义验证。@SanthoshK我是这样做的,就像validate do | model1 | model1。如果model1.model12s.blank,错误(“必须选择”)?结束,但这里也有同样的问题,这个“if model1.model12s”返回的是旧值,单位是DB。这对我来说很有用。validate:address\u present def address\u present self.errors.add(:name,“不能为空”)如果self.addresses.size==0 end那么关于:validates:model12\u id,:length=>{:minimum=>1}呢?这对我来说很有效,但有一个has_和_属于许多协会。“但我想基本上是一样的。”桑托什克谢谢你的承诺,我试过了。这对我也不起作用(
class model1 < ActiveRecord::Base

  has_many :model12, :dependent => :destroy, :include => [:model]
  has_many :model2, :through => :model12, :uniq => true

  accepts_nested_attributes_for :model2,
    :allow_destroy => true,
    :reject_if => proc {|m| m.blank? }

  validate :must_have_one_model2

  def must_have_one_model2
    errors.add(:model2s, 'must have one model2') if model12s_count_valid?
  end

  def model12s_count_valid?
    model12s.reject(&:marked_for_destruction?).count >= 1
  end
end