Check Rails model after saving?

I have a model with several accepts_nested_attributes_for. There is a requirement that when saving and moving I have at least one of each of the nested attributes.

However, the check is done previously, so when I delete an item and move it, it skips it.

How can I verify that when I saved, I have at least one element of each nested type?

+3
source share
3 answers

There is an error with accepts_nested_attributes_for . That means you have to be a little trickier when it comes to checks in the parent model.

after_save , , . , , .

, , :

class Whatever < ActiveRecord::Base
  :has_many => :association_a
  :has_many => :association_b

  def ensure_minimum_associations
    bad_associations =  [:association_a, :association_b].
      select{|assoc| self.send(assoc).all?{|a| a.marked_for_destruction?}}
    unless bad_associations.empty?
      bad_associations.each do |association|
        errors.add_to_base "Each #{self.class.name.downcase} must retain at least one #{association}"
      end
      return false
    end
  end
end
+6

valid? .

0

I believe you are looking for validates_associated

0
source

Source: https://habr.com/ru/post/1719890/


All Articles