14

我有两个模型:ProjectProjectDiscipline

class Project < ActiveRecord::Base
  has_many :project_disciplinizations, :dependent => :destroy
  has_many :project_disciplines, through: :project_disciplinizations
  attr_accessible :project_discipline_ids
  attr_accessible :project_disciplines_attributes
  accepts_nested_attributes_for :project_disciplines, :reject_if => proc { |attributes| attributes['name'].blank? }
end

class ProjectDiscipline < ActiveRecord::Base
  attr_accessible :name
  has_many :project_disciplinizations, :dependent => :destroy
  has_many :projects, through: :project_disciplinizations
end

class ProjectDisciplinization < ActiveRecord::Base
  attr_accessible :project_discipline_id, :project_id
  belongs_to :project_discipline
  belongs_to :project
end

在新/编辑Project表单上,我有一个学科列表和每个学科的复选框,因此用户可以选择学科:

<div class="control-group">
  <label class="control-label">Check disciplines that apply</label>
  <div class="controls">
    <%= f.collection_check_boxes(:project_discipline_ids, ProjectDiscipline.order('name'), :id, :name, {}, {:class => 'checkbox'}) {|input| input.label(:class => 'checkbox') { input.check_box + input.text }} %>
    <p class="help-block">You must choose at least one discipline.</p>
  </div>
</div>

我想添加一个验证以要求至少检查一个学科。我已经尝试过,但我还没有弄清楚。如何添加此验证?

4

3 回答 3

17

答案前的旁注,根据您的模型结构,我将使用 has_and_belongs_to_many 而不是使用此显式链接模型,因为链接模型似乎没有增加任何价值。

不管怎样,答案都是一样的,那就是使用自定义验证。取决于您是按原样处理事情还是简化为 has_and_belongs_to 许多人,您会希望进行稍微不同的验证。

validate :has_project_disciplines

def has_project_disciplines
  errors.add(:base, 'must add at least one discipline') if self.project_disciplinizations.blank?
end

或与 has_and_belongs_to_many

validate :has_project_disciplines

def has_project_disciplines
  errors.add(:base, 'must add at least one discipline') if self.project_disciplines.blank?
end
于 2013-07-23T14:49:15.247 回答
15

我更喜欢更简单的方法:

class Project < ActiveRecord::Base
  validates :disciplines, presence: true
end

validates_presence_of由于漏洞利用blank?方法,此代码与 John Naegle 或 Alex Peachey 的代码完全相同。

于 2015-06-20T07:05:58.667 回答
4

您可以编写自己的验证器

class Project < ActiveRecord::Base

  validate :at_least_one_discipline

  private
  def at_least_one_discipline
    # Check that at least one exists after items have been de-selected
    unless disciplines.detect {|d| !d.marked_for_destruction? }
      errors.add(:disciplines, "must have at least one discipline")
    end
  end
end
于 2013-07-23T14:50:10.050 回答