Aleksandr K.
Aleksandr K.

Reputation: 1415

Before save action and validation

My application has a logic: Parent model before save generates child model elements.

I'd like to validate before save parent element that it has at least one child element.

I tried use validates_presence_of, but it called before 'before_save' so parent doesn't have child elements.

Could you please tell me where I should generate child elements and where validate presence or absence of child elements?

Upvotes: 0

Views: 4059

Answers (2)

koyz
koyz

Reputation: 154

Correct me if I misunderstood your problem, but you want to check if Parent model has at least 1 child before the Parent model triggers 'before_save' callback (which will do whatever it wants), right?

If yes, you can use 'before_validation' callback. 'before_validation' is called before 'before_save'. So you can do something like:

before_validation { self.errors.add(:base, 'error here or something') if self.children.count < 1 }

Note that rails will not even try to save the resource if resource's 'errors' array is not empty (so before_save callback will not be called). doing 'self.errors.add' in the 'before_save' callback will not stop the resource from being saved. If you want to stop the resource from being saved from the 'before_save' callback you can do:

before_save do 
  self.errors.add(:base, 'error here or something')
  false
end

Hope that helped. :)

Cheers!

Upvotes: 2

nikolayp
nikolayp

Reputation: 17919

Something like this:

class Hero < ActiveRecord::Base
  has_many :weapons

  before_save :check_equipment

  private
    def check_equipment
      errors.add(:weapons, "are not equipped") if weapons.size < 1 
    end
end

class Weapon < ActiveRecord::Base
  belongs_to :hero
end

You can create weapon as independent object and then associate the weapon with heros, or you can also create weapon with the hero just use accepts_nested_attributes_for method. The solution depends on you application architecture.

Upvotes: 0

Related Questions